Flatten Nested Object into target object with GSON

痞子三分冷 提交于 2019-12-02 05:38:40

You can write a custom type adapter to map json value to your pojo.

Define a pojo:

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

Write a custom 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!");
    }
}

Test:

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

Output:

About TypeAdapter:

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!