如何迭代JSONObject(gson) [英] How to iterate a JSONObject (gson)
问题描述
我有一个JsonObject例如
JsonObject jsonObject = {keyInt:2,keyString:val1, id:0123456}
每个JSONObject都包含一个id条目,其他键/值对不确定,所以我想创建一个具有2个属性的对象:
class myGenericObject {
Map< String,Object>属性;
字符串ID;
$ / code>
所以我希望我的属性映射如下所示:
keyInt - > 4711
keyStr - > val1
我发现这个解决方案
映射< String,Object> attributes = new HashMap< String,Object>();
Set< Entry< String,JsonElement>> entrySet = jsonObject.entrySet(); (Map.Entry< String,JsonElement>条目:entrySet){
attributes.put(entry.getKey(),jsonObject.get(entry.getKey()));
}
但是这些值包含在
keyInt - > 4711
keyStr - > val1
如何获取普通值(4711和val1)? p>
输入数据:
{
id:0815 ,
a:a string,
b:123.4,
c:{
a:1,
b :true,
c:[a,b,c]
}
}
或
{
id:4711,
x:false,
y:y?,
}
<
Map< String,解决方案对象> attributes = new HashMap< String,Object>();
Set< Entry< String,JsonElement>> entrySet = jsonObject.entrySet(); (Map.Entry< String,JsonElement> entry:entrySet){
if(!nonProperties.contains(entry.getKey())){
properties.put(entry.getKey ),jsonObject.get(entry.getKey())。replace(\,));
}
}
I have a JsonObject e.g
JsonObject jsonObject = {"keyInt":2,"keyString":"val1","id":"0123456"}
Every JSONObject contains a "id" entry, but th number of other key/value pairs is NOT determined, so I want to create create an object with 2 attributes:
class myGenericObject {
Map<String, Object> attributes;
String id;
}
So I want my attributes map to look like this:
"keyInt" -> 4711
"keyStr" -> "val1"
I found this solution
Map<String, Object> attributes = new HashMap<String, Object>();
Set<Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
for(Map.Entry<String,JsonElement> entry : entrySet){
attributes.put(entry.getKey(), jsonObject.get(entry.getKey()));
}
but the values are enclosed by ""
"keyInt" -> "4711"
"keyStr" -> ""val1""
How to get the plain values (4711 and "val1")?
Input data:
{
"id": 0815,
"a": "a string",
"b": 123.4,
"c": {
"a": 1,
"b": true,
"c": ["a", "b", "c"]
}
}
or
{
"id": 4711,
"x": false,
"y": "y?",
}
replace "" with blank.
Map<String, Object> attributes = new HashMap<String, Object>();
Set<Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
for(Map.Entry<String,JsonElement> entry : entrySet){
if (! nonProperties.contains(entry.getKey())) {
properties.put(entry.getKey(), jsonObject.get(entry.getKey()).replace("\"",""));
}
}
这篇关于如何迭代JSONObject(gson)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!