Parse jsonObject when field names are unknowm

最后都变了- 提交于 2019-12-13 02:01:23

问题


I'm trying to extract some data from a JsonObject. The problem is that the fields that come inside that json have unpredictable names.

How can I extract that information having this weird field names?

Here is an example:

 "myObject":{  
          "216cfa89a2de57554b36b177f0bfbb05":{  

           },
           "0cf9182b5ceba2cb64174141a13e647d":{  

           },
           "eb1d1b19e117ba1387a798d9194b4660":{  

           },
           "157b52871e8e560c7ec0be111ef02363":{  

           },
           "4db69dd3a8ae8e0089bd2959ab0c5f86":{  

           },
}

I'm using gson, where we have the method getAsJsonObject, but how can I use it if I don't know the field names?

JsonObject jsonObject= myObjectJsonObject.getAsJsonObject("???");    

Also, there can be a variable number of fields, and this is a problem too. I wonder why I don't get an jsonArray as a response, it would be more suitable and I could have parse it that way.


回答1:


Use the JsonObject.entrySet().

    String json = "{ 'abcd': { 'a':'d' }, 'dcba': { 'd':'a' } }";
    JsonObject o = new JsonParser().parse(json).getAsJsonObject();

    for(Map.Entry<String, JsonElement> entry : o.entrySet()) {
        System.out.println(entry.getKey());
        System.out.println(entry.getValue());
    }

Or you could get a map when you load the object:

    Map<String, JsonObject> map = new Gson().fromJson(json, new TypeToken<Map<String, JsonObject>>(){}.getType());
    for(Map.Entry e : map.entrySet()) {
        System.out.println(e.getKey());
        System.out.println(e.getValue());
    }
}

Or you could add a JsonDeserializer which can deserialize your class into something sensible (likely a map).




回答2:


In your case its beter to use JsonPath

With JSON like this :

{
  "myObject": {
    "216cfa89a2de57554b36b177f0bfbb05": {
      "field1": true
    },
    "0cf9182b5ceba2cb64174141a13e647d": {
      "field2": true
    },
    "eb1d1b19e117ba1387a798d9194b4660": {
      "field3": true
    },
    "157b52871e8e560c7ec0be111ef02363": {
      "field2": true
    },
    "4db69dd3a8ae8e0089bd2959ab0c5f86": {
      "field5": true
    }
  }
}

And an expretion of JsonPth

$.myObject.*

You will get an array of fields

[
  {
    "field1": true
  },
  {
    "field2": true
  },
  {
    "field3": true
  },
  {
    "field2": true
  },
  {
    "field5": true
  }
]

Hope that help :)




回答3:


JsonObject o = new JsonParser().parse("some json string").getAsJsonObject();



回答4:


If you look at this post you see that you can simply do:

Object o = new Gson().fromJson(json, Object.class);

The object returned is a Map of String and either String or a Map.



来源:https://stackoverflow.com/questions/33647148/parse-jsonobject-when-field-names-are-unknowm

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