当字段名称未知时解析jsonObject [英] Parse jsonObject when field names are unknowm

查看:199
本文介绍了当字段名称未知时解析jsonObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从JsonObject中提取一些数据。
问题是进入该json的字段有不可预知的名称。

如何提取含有这些奇怪字段名称的信息?



下面是一个例子:

 myObject:{
216cfa89a2de57554b36b177f0bfbb05:{

},
0cf9182b5ceba2cb64174141a13e647d:{

},
eb1d1b19e117ba1387a798d9194b4660:{

},
157b52871e8e560c7ec0be111ef02363:{

},
4db69dd3a8ae8e0089bd2959ab0c5f86:{

},
}

我使用gson,在那里我们有方法getAsJsonObject,但是如果我不知道字段名称?

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

另外,可以有不定数量的字段,这也是一个问题。
我想知道为什么我没有得到一个jsonArray作为回应,它会更合适,我可以用这种方式解析它。

解决方案

使用 JsonObject.entrySet()

  String json ={'abcd' :{'a':'d'},'dcba':{'d':'a'}}; 
JsonObject o = new JsonParser()。parse(json).getAsJsonObject(); (Map.Entry< String,JsonElement> entry:o.entrySet()){
System.out.println(entry.getKey());


System.out.println(entry.getValue());
}

或者您可以在加载对象时获得地图:

 映射< 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());


或者你可以添加一个 JsonDeserializer ,它可以将你的类反序列化为合理的东西(可能是一张地图)。

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.

解决方案

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

这篇关于当字段名称未知时解析jsonObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆