使用GSON将嵌套对象展平为目标对象

时间:2015-01-20 20:56:04

标签: android gson ormlite

最亲爱的Stackoverflowers,

我想知道是否有人知道如何以最佳方式解决这个问题; 我正在和一个api交谈,它返回一个像这样的json对象:

{
   "field1": "value1",
   "field2": "value2",
   "details": {
      "nested1": 1,
      "nested2": 1

}

在java中我有一个对象(实体),例如,它将具有所有这些字段,但是细节为松散字段,因此: field1,field2,nested1,nested2。

这是因为它是一个Android项目,我不能将一个带有信息的课程保存到我的实体中,因为我已经绑定了ormlite。

有没有办法使用GSON将字段平移到我的对象中?请注意,我现在使用通用类直接从API转换这些类。我想存储这些字段(包含int的信息)。在同一个实体中。

1 个答案:

答案 0 :(得分:2)

您可以编写自定义类型适配器以将json值映射到您的pojo。

定义一个pojo:

public class DataHolder {
    public List<String> fieldList;
    public List<Integer> detailList;
}

撰写自定义typeAdapter:

public class CustomTypeAdapter extends TypeAdapter<DataHolder> {
    public DataHolder read(JsonReader in) throws IOException {
        final DataHolder dataHolder = new DataHolder();

        in.beginObject();

        while (in.hasNext()) {
            String name = in.nextName();

            if (name.startsWith("field")) {
                if (dataHolder.fieldList == null) {
                    dataHolder.fieldList = new ArrayList<String>();
                }
                dataHolder.fieldList.add(in.nextString());
            } else if (name.equals("details")) {
                in.beginObject();
                dataHolder.detailList = new ArrayList<Integer>();
            } else if (name.startsWith("nested")) {
                dataHolder.detailList.add(in.nextInt());
            }
        }

        if(dataHolder.detailList != null) {
            in.endObject();
        }
        in.endObject();

        return dataHolder;
    }

    public void write(JsonWriter writer, DataHolder value) throws IOException {
        throw new RuntimeException("CustomTypeAdapter's write method not implemented!");
    }
}

<强>测试

    String json = "{\"field1\":\"value1\",\"field2\":\"value2\",\"details\":{\"nested1\":1,\"nested2\":1}}";

    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(DataHolder.class, new CustomTypeAdapter());

    Gson gson = builder.create();

    DataHolder dataHolder = gson.fromJson(json, DataHolder.class);

<强>输出: enter image description here

关于TypeAdapter:

https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/TypeAdapter.html

http://www.javacreed.com/gson-typeadapter-example/

相关问题