How to get String from JSONObject without Specific Name

五迷三道 提交于 2019-12-04 11:31:56

问题


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.

So how can I get the "objectString" without specific key like "EntryPointJsonResult"


回答1:


You can get values of json object like this without knowing key

Iterator<String> keys= object.keys();
while (keys.hasNext()) 
{
        String keyValue = (String)keys.next();
        String valueString = object.getString(keyValue);
}



回答2:


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.



来源:https://stackoverflow.com/questions/26255089/how-to-get-string-from-jsonobject-without-specific-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!