[英]Java: Parsing Json with Gson for unknown field
I making an parser for json with gson and it based on object model method. 我使用gson和基于对象模型方法的json解析器。 My problem is that I have an object on the json where there are some other JsonObjects in it but I don't know there names so I can't use the SerializedName.
我的问题是,我在json上有一个对象,其中有一些其他JsonObjects,但我不知道那里的名称,因此无法使用SerializedName。 Also the number of the JsonObjects on the initial object is random.
同样,初始对象上JsonObjects的数量是随机的。 How to iterate the objects from the initial object?
如何从初始对象迭代对象?
Json style: 杰森风格:
"initial_obj": {
"random_name1": { }
"random_name50": { }
"random_name9": { }
}
If the name of fields are not known in advance then convert it into Map<String, Object>
using TypeToken
如果字段名称事先未知,则使用
TypeToken
将其转换为Map<String, Object>
String str = "{\"initial_obj\": {\"random_name1\": { },\"random_name50\": { },\"random_name9\": { }}}";
Type type = new TypeToken<Map<String, Object>>() {}.getType();
Map<String, Object> data = new Gson().fromJson(str, type);
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(data));
output: 输出:
{
"initial_obj": {
"random_name1": {},
"random_name50": {},
"random_name9": {}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.