用变量键分析json [英] Parse json with variable key
问题描述
以下是json响应,其中key是可变的(GUID)
我该如何解析它?
{
87329751-7493-7329- uh83-739823748596:{
type:work,
status:online,
icon:固定电话,
号码: 102,
display_number:+999999999
}
}
Map< String,SomeObject>
就是你的JSON所代表的,因为你有一个> 对象
p> {someString:{...}}
因此,首先包含JSON数据的类(在伪代码中):
class YourClass
字符串类型
字符串状态
字符串图标
整数
字符串display_number
然后使用 Map
来解析您的JSON响应,如下所示:
Gson gson = new Gson();
Type type = new TypeToken< Map< String,YourClass>>(){} .getType();
地图< String,YourClass> map = gson.fromJson(jsonString,type);
现在您可以使用 Map $ c $例如:
String GUID = map.keySet()。get(0);
String type = map.get(GUID).getType();
注意:如果您只想获取GUID值,则不需要创建类 YourClass
,您可以使用相同的解析代码,但在中使用通用的
,即 Object
Map Map< String,Object>
。
I just came up with challenging problem.
Below is json response where key is variable (a GUID)
How can I parse it? I've tried Google Gson, but that didn't work.
{
"87329751-7493-7329-uh83-739823748596": {
"type": "work",
"status": "online",
"icon": "landline",
"number": 102,
"display_number": "+999999999"
}
}
If you use Gson, in order to parse your response you can create a custom class representing your JSON data, and then you can use a Map
.
Note that a Map<String, SomeObject>
is exactly what your JSON represents, since you have an object
, containing a pair of string
and some object
:
{ "someString": {...} }
So, first your class containing the JSON data (in pseudo-code):
class YourClass
String type
String status
String icon
int number
String display_number
Then parse your JSON response using a Map
, like this:
Gson gson = new Gson();
Type type = new TypeToken<Map<String, YourClass>>() {}.getType();
Map<String, YourClass> map = gson.fromJson(jsonString, type);
Now you can access all the values using your Map
, for example:
String GUID = map.keySet().get(0);
String type = map.get(GUID).getType();
Note: if you only want to get the GUID value, you don't need to create a class YourClass
, and you can use the same parsing code, but using a generic Object
in the Map
, i.e., Map<String, Object>
.
这篇关于用变量键分析json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!