Gson custom deserialization

笑着哭i 提交于 2019-12-12 13:19:56

问题


I'm using Gson to create and parse JSON, but I've faced one problem. In my code I use this field:

@Expose
private ArrayList<Person> persons = new ArrayList<Person>();

But my JSON is formated like this:

persons:{count:"n", data:[...]}

Data is an array of persons.

Is there any way to convert this JSON into my class using Gson? Can I use a JsonDeserializer?


回答1:


You'll need a custom deserializer (http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/JsonDeserializer.html), something like:

  public static class MyJsonAdapter implements JsonDeserializer<List<Person>>
  {
    List<Person> people = new ArrayList<>();
    public List<Person> deserialize( JsonElement jsonElement, Type type, JsonDeserializationContext context )
      throws JsonParseException
    {
      for (each element in the json data array) 
      {
        Person p = context.deserialize(jsonElementFromArray,Person.class );
        people.add(p);
      }
    }
    return people;
  }



回答2:


You can try below code to parse your json

String jsonInputStr = "{count:"n", data:[...]}";

Gson gson = new Gson();
JsonObject jsonObj = gson.fromJson(jsonInputStr, JsonElement.class).getAsJsonObject();
List<Person> persons = gson.fromJson(jsonObj.get("data").toString(), new TypeToken<List<Person>>(){}.getType());


来源:https://stackoverflow.com/questions/17730345/gson-custom-deserialization

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!