java 如何从没有特定名称的 JSONObject 获取字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26255089/
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 get String from JSONObject without Specific Name
提问by Droid
Please check this code sample.
请检查此代码示例。
HttpEntity getResponseEntity = getResponse.getEntity();
String message = EntityUtils.toString(getResponseEntity,"UTF-8");
//message = {"EntryPointJsonResult":"{\"NextTransactionUrl\":null,\"TraceId\":null,\"IsAuthorizationRequired\":false,\"IsError\":false,\"ErrorCode\":null,\"ErrorMessage\":null}"}
JSONObject object = new JSONObject(message);
String objectString = object.getString("EntryPointJsonResult");
//objectString = {\"NextTransactionUrl\":null,\"TraceId\":null,\"IsAuthorizationRequired\":false,\"IsError\":false,\"ErrorCode\":null,\"ErrorMessage\":null}
That's the question : I want to get the "objectString" without "EntryPointJsonResult". Cause this information is different at the another response.
这就是问题:我想获得没有“EntryPointJsonResult”的“objectString”。因为这个信息在另一个响应中是不同的。
So how can I get the "objectString" without specific key like "EntryPointJsonResult"
那么如何在没有像“EntryPointJsonResult”这样的特定键的情况下获得“objectString”
回答by Amy
You can get values of json object like this without knowing key
您可以在不知道密钥的情况下获取这样的 json 对象的值
Iterator<String> keys= object.keys();
while (keys.hasNext())
{
String keyValue = (String)keys.next();
String valueString = object.getString(keyValue);
}
回答by ToYonos
This should work.
这应该有效。
JSONObject object = new JSONObject(message);
String objectString = object.getString(object.names().get(0));
But it will only work if you sure that NextTransactionUrl
node exists. By the way, in this case, this node could have another name, it will still work.
但它只有在您确定该NextTransactionUrl
节点存在时才有效。顺便说一下,在这种情况下,这个节点可以有另一个名字,它仍然可以工作。