Gson定制反序列化

Ger*_*ore 3 java json gson

我正在使用Gson来创建和解析JSON,但我遇到了一个问题.在我的代码中,我使用此字段:

@Expose
private ArrayList<Person> persons = new ArrayList<Person>();
Run Code Online (Sandbox Code Playgroud)

但我的JSON格式如下:

persons:{count:"n", data:[...]}
Run Code Online (Sandbox Code Playgroud)

数据是一系列人.

有没有办法使用Gson将此JSON转换为我的类?我可以使用JsonDeserializer吗?

Chr*_*sel 6

您需要一个自定义反序列化器(http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/JsonDeserializer.html),例如:

  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;
  }
Run Code Online (Sandbox Code Playgroud)


Pur*_*ham 5

您可以尝试下面的代码来解析您的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());
Run Code Online (Sandbox Code Playgroud)