简体   繁体   中英

How to get string array from json object in deserialize method

I have some json object

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

Here is my implementation of 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);
    }
}

How to get string array from json object here using GSON library?

Thanks a lot!

For the deserializer you can just loop over the ArrayNode and add the values to your String[] one after another.

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();

Try this this will work for you. Thanks.

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();
        }
    }
}

I want to thank all who responded on my question and in the same time i find my decision (which is below) as the most fitting answer. Because i don't need to use any other libraries except GSON. When i asked my question i didn't know that com.google.gson.TypeAdapter is more efficient instrument than JsonSerializer/JsonDeserializer. And here below i have found decision for my problem:

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);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM