GSON序列化和反序列化列表委托者

时间:2014-09-03 09:10:45

标签: java json gson

我有一个实现List<T>的类并包装它委派的ArrayList<T>。 这样的事情:

class ListWrapper<T> implements List<T> {   
      private String id;  
      private List<T> list = new ArrayList<T>();    
      private transient ListListener listener;   

      // all of List  interface methods are delegated here e.g.   
      public void add(T t) {
           list.add(t);    
           listener.onItemAdded(id);
      }
      ...
}

GSON默认行为是将此事件视为List,因此它不会调用字段级反射。

我想像这样得到一个json:

{
 id="1234",
 list=[....]
}

关于如何优雅地做到这一点的任何想法?

1 个答案:

答案 0 :(得分:0)

在这种情况下,您可以使用自定义TypeAdapter。

示例:

class ListWrapper<T> extends ArrayList<T>
{
    private static final long serialVersionUID = 1L;

    String id = "asd";
    List<T> list = new ArrayList<T>();
    transient T listener = null;
}

创建自定义TypeAdapter

   class CustomTypeAdapter<T> extends TypeAdapter<ListWrapper<T>>
{

    @Override
    public void write(JsonWriter writer, ListWrapper<T> value) throws IOException
    {
        if (value == null)
        {
            writer.nullValue();
            return;
        }

        writer.beginObject();

        // Add id field
        writer.name("id").value(value.id);

        // Add list field
        StringBuilder builder = new StringBuilder("");
        builder.append("list : [ ");
        for (T t : value.list)
        {
            builder.append("T : " + t.toString() + ",");
        }
        String txt = builder.substring(0, builder.length() - 1) + "]";
        writer.name("list").value(StringUtils.join(value.list, ";"));

        // Add other fields
        // TODO

        writer.endObject();
    }
    @Override
    public ListWrapper<T> read(JsonReader in) throws IOException
    {
        // Implement your deserialization logic here
        return null;
    }
}

样本用法:

 public static void main(String[] args)
    {

        GsonBuilder builder = new GsonBuilder();
        builder.registerTypeAdapter(ListWrapper.class, new CustomTypeAdapter<String>());
        Gson gson = builder.create();
        ListWrapper<String> lw = new ListWrapper<String>();
        lw.list.add("as");
        lw.list.add("is");
        System.out.println(gson.toJson(lw));
    }

示例输出JSON:

 {"id":"asd","list":"as;is"}