Gson自定义反序列化 [英] Gson custom deserialization

查看:298
本文介绍了Gson自定义反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

但是我的JSON格式如下:

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

数据是一个人数组。

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

解决方案

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

  public static class MyJsonAdapter实现JsonDeserializer< List< Person>> 
{
列表< Person> people = new ArrayList<>();
public List< Person> deserialize(JsonElement jsonElement,Type类型,JsonDeserializationContext上下文)
抛出JsonParseException
{
for(json数据数组中的每个元素)
{
Person p = context。反序列化(jsonElementFromArray,Person.class);
people.add(p);
}
}
返回人员;
}


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?

解决方案

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

这篇关于Gson自定义反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆