Gson自定义反序列化

3

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

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

但我的JSON格式是这样的:
persons:{count:"n", data:[...]}

数据是一个人的数组。

有没有办法使用 Gson 将这个 JSON 转换成我的类?我可以使用 JsonDeserializer 吗?

2个回答

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

我尝试了你的解决方案,但仍然出现“IllegalStateException:Expected BEGIN_ARRAY but was BEGIN_OBJECT”。这是我的实现:http://pastebin.com/4ZYs0S9A - Geralt_Encore
这基本上是伪代码,不是你可以直接使用的东西。你需要获取与数据对应的正确元素,然后解析它。请参见此处的反序列化方法(从1089开始),这是我曾经编写过的一个复杂的反序列化程序:https://github.com/chriskessel/MyHex/blob/master/src/kessel/hex/domain/Player.java - Chris Kessel
谢谢回复!我之前一直无法处理序列化器,但现在似乎终于搞懂了。 - Geralt_Encore

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

实际上我是这样做的。 - Geralt_Encore

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接