【问题标题】:How to get string array from json object in deserialize method如何在反序列化方法中从json对象获取字符串数组
【发布时间】:2018-02-14 14:22:55
【问题描述】:

我有一些 json 对象

{
  "name": "John",
  "age": 29,
  "bestFriends": [
    "Stan",
    "Nick",
    "Alex"
  ]
}

这是我的 JsonDeserializer 实现:

public class CustomDeserializer implements JsonDeserializer<Person>{
    @Override
    public Person deserialize(JsonElement json, Type type, JsonDeserializationContext cnxt){
        JsonObject object = json.getAsJsonObject();
        String name = new String(object.get("name").getAsString());
        Integer age = new Integer(object.get("age").getAsInt());
        String bestFriends[] = ?????????????????????????????????
        return new Person(name, age, bestFriends);
    }
}

如何使用 GSON 库从此处的 json 对象中获取字符串数组?

非常感谢!

【问题讨论】:

    标签: java json gson json-deserialization


    【解决方案1】:

    对于反序列化器,您可以循环遍历 ArrayNode 并将值一个接一个地添加到您的 String[] 中。

    ArrayNode friendsNode = (ArrayNode)object.get("bestFriends");
    List<String> bestFriends = new ArrayList<String>();
    for(JsonNode friend : friendsNode){
       bestFriends.add(friend.asText());
    }
    //if you require the String[]
    bestFriends.toArray();
    

    【讨论】:

    【解决方案2】:

    试试这个对你有用。谢谢。

    package test;
    
    import java.io.IOException;
    
    import com.fasterxml.jackson.core.JsonParseException;
    import com.fasterxml.jackson.databind.JsonMappingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    
    
    class ID{
    
        private String id;
    
        public String getId() {
            return id;
        }
    
        public void setId(String id) {
            this.id = id;
        }
    
        @Override
        public String toString() {
            return "ID [id=" + id + "]";
        }
    
    }
    public class Test {
    
        public static void main(String[] args) {
            ObjectMapper mapper = new ObjectMapper();
            String jsonText = "{\"id\" : \"A001\"}";
    
    
    
            //convert to object
            try {
                ID id = mapper.readValue(jsonText, ID.class);
                System.out.println(id);
            } catch (JsonParseException e) {
    
                e.printStackTrace();
            } catch (JsonMappingException e) {
    
                e.printStackTrace();
            } catch (IOException e) {
    
                e.printStackTrace();
            }
        }
    }
    

    【讨论】:

      【解决方案3】:

      我要感谢所有回答我的问题的人,同时我发现我的决定(如下)是最合适的答案。因为我不需要使用除 GSON 之外的任何其他库。 当我问我的问题时,我不知道 com.google.gson.TypeAdapter 是比 JsonSerializer/JsonDeserializer 更有效的工具。 在下面,我为我的问题找到了决定:

      package mytypeadapter;
      import com.google.gson.Gson;
      import java.io.IOException;
      import java.util.List;
      import java.util.ArrayList;
      import com.google.gson.GsonBuilder; 
      import com.google.gson.TypeAdapter;
      import com.google.gson.stream.JsonReader;
      import com.google.gson.stream.JsonWriter;
      
      public class Main {
          static class Person{ 
             String name; 
             int age; 
             String[] bestFriends; 
      
             Person() {}       
             Person(String name, int population, String... cities){ 
                this.name = name; 
                this.age = population; 
                this.bestFriends = cities; 
             } 
          }    
      
          public static void main(String[] args) {
              class PersonAdapter extends TypeAdapter<Person>{
                  @Override 
                  public Person read (JsonReader jsonReader) throws IOException{
                      Person country = new Person();
                      List <String> cities = new ArrayList<>();
                      jsonReader.beginObject();
                      while(jsonReader.hasNext()){
                          switch(jsonReader.nextName()){
                              case "name":
                                  country.name = jsonReader.nextString();
                                  break;
                              case "age":
                                  country.age = jsonReader.nextInt();
                                  break;
                              case "bestFriends":
                                  jsonReader.beginArray();
                                  while(jsonReader.hasNext()){
                                      cities.add(jsonReader.nextString());
                                  }
                                  jsonReader.endArray();
                                  country.bestFriends = cities.toArray(new String[0]);
                                  break;                          
                          }
                      }
                      jsonReader.endObject();
                      return country;             
                  }
      
                  @Override
                  public void write (JsonWriter jsonWriter, Person country) throws IOException{
                      jsonWriter.beginObject();
                      jsonWriter.name("name").value(country.name);
                      jsonWriter.name("age").value(country.age);
                      jsonWriter.name("bestFriends");
                      jsonWriter.beginArray();
                      for(int i=0;i<country.bestFriends.length;i++){
                          jsonWriter.value(country.bestFriends[i]);
                      }
                      jsonWriter.endArray();
                      jsonWriter.endObject();
                  }
              }
              Gson gson = new GsonBuilder()
                          .registerTypeAdapter(Person.class, new PersonAdapter())
                          .setPrettyPrinting()
                          .create();
              Person person, personFromJson;
              person = new Person ("Vasya", 29, "Stan", "Nick", "Alex");
              String json = gson.toJson(person); 
              personFromJson = new Person();
              personFromJson = gson.fromJson(json, personFromJson.getClass());
              System.out.println("Name = "+ personFromJson.name);
              System.out.println("Age = "+ personFromJson.age);
              for(String friend : personFromJson.bestFriends){
                  System.out.println("Best friend "+ friend);
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-06-06
        • 2022-09-23
        • 1970-01-01
        • 2014-10-08
        • 2012-03-31
        • 2021-05-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多