How to deserialize JSON into flat, Map-like structure?

后端 未结 7 2072
醉梦人生
醉梦人生 2020-12-01 06:34

Have in mind that the JSON structure is not known before hand i.e. it is completely arbitrary, we only know that it is JSON format.

For example,

The followin

相关标签:
7条回答
  • 2020-12-01 07:36

    how about that:

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Map.Entry;
    import com.google.gson.Gson;
    
    /**
     * NOT FOR CONCURENT USE
    */
    @SuppressWarnings("unchecked")
    public class JsonParser{
    
    Gson gson=new Gson();
    Map<String, String> flatmap = new HashMap<String, String>();
    
    public Map<String, String> parse(String value) {        
        iterableCrawl("", null, (gson.fromJson(value, flatmap.getClass())).entrySet());     
        return flatmap; 
    }
    
    private <T> void iterableCrawl(String prefix, String suffix, Iterable<T> iterable) {
        int key = 0;
        for (T t : iterable) {
            if (suffix!=null)
                crawl(t, prefix+(key++)+suffix);
            else
                crawl(((Entry<String, Object>) t).getValue(), prefix+((Entry<String, Object>) t).getKey());
        }
    }
    
    private void crawl(Object object, String key) {
        if (object instanceof ArrayList)
            iterableCrawl(key+"[", "]", (ArrayList<Object>)object);
        else if (object instanceof Map)
            iterableCrawl(key+".", null, ((Map<String, Object>)object).entrySet());
        else
            flatmap.put(key, object.toString());
    }
    }
    
    0 讨论(0)
提交回复
热议问题