Flatten Nested Object into target object with GSON

前端 未结 1 1389
挽巷
挽巷 2021-01-21 13:46

Dearest Stackoverflowers,

I was wondering if anyone knows how to solve this the best way; I\'m talking to an api which returns a json object like this:

{         


        
相关标签:
1条回答
  • 2021-01-21 14:31

    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: enter image description here

    About TypeAdapter:

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

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

    0 讨论(0)
提交回复
热议问题