java 如何在java中获取JSON对象的所有节点和子节点?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31019391/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to fetch all the nodes and child nodes of JSON object in java?
提问by AGM
I want to fetch all the nodes of the below JSON object. For example
result, identification, payment etc.
我想获取以下 JSON 对象的所有节点。例如
结果、身明、付款等。
{
"result": {
"identification": {
"transactionid": "Merchant Assigned ID",
"uniqueid": "d91ac8ff6e9945b8a125d6e725155fb6",
"shortid": "0000.0005.6238",
"customerid": "customerid 12345"
},
"payment": {
"amount": "2400",
"currency": "EUR",
"descriptor": "order number"
},
"level": 0,
"code": 0,
"method": "creditcard",
"type": "preauthorization",
"message": "approved",
"merchant": {
"key1": "Value1",
"key0": "Value0"
}
},
"id": 1,
"jsonrpc": "2.0"
}
I have used the following code:
我使用了以下代码:
JSONObject partsData = new JSONObject(returnString);
Iterator<String> iterator = jsonObject.keys();
while (iterator.hasNext()) {
String result=iterator.next();
System.out.println(result);
}
But the result I am getting is:
但我得到的结果是:
id
result
jsonrpc
How do I get all the node names?
如何获取所有节点名称?
回答by Waqar
Move your iterator logic (to iterate over json) in a method
e.g.,
在方法中移动您的迭代器逻辑(以迭代 json),
例如,
public Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{
Iterator<String> keys = json.keys();
while(keys.hasNext()){
String key = keys.next();
String val = null;
if ( json.getJSONObject(key) instanceof JSONObject ) {
JSONObject value = json.getJSONObject(key);
parse(value,out);
}
else {
val = json.getString(key);
}
if(val != null){
out.put(key,val);
}
}
return out;
}
This way you can check for each sub node in the json object.
这样您就可以检查 json 对象中的每个子节点。
回答by Vinay
You have to parse through all the objects.
您必须解析所有对象。
JSONObject partsData = new JSONObject("result");
JsonObject identification = partsData.getJsonObject("identification");
JsonObject payment = partsData.getJsonobject("payment");