问题
Hello every one I need your help for reading the random named array from the json object.
In this task client make the json object according to his requirements.
like
{
"tags":[ "demo 1","demo 2","demo 3","demo 4","demo 5","N" ]
}
I'm using "N" for defining the unlimited numbers of items in one array.
Here in This code user use tags key to put json Array in json object.
User can also make emphasized textarray as Clients
{
"Clients":[ "demo 1","demo 2","demo 3","demo 4","demo 5","N" ]
}
I know how to parse
JSONArray jsonMainArr = new JSONArray(String.valueOf(ObjectName.getJSONArray("Keyname")));
Now my Question is How to get Json Array if we Don't Know the KeyName like tags or Clients
回答1:
You can do something like this:
JSONObject mainJsonObject = new JSONObject(jsonString);
Iterator<?> keys = mainJsonObject.keys();
if (keys.hasNext()){
String key = (String) keys.next();
JSONArray jsonMainArr = mainJsonObject.getJSONArray(key);
}
In the above code I am getting the main JsonObject from the original jsonString and using the iterator getting the first key inside the object and using it to fetch the JsonArray.
Try this solution and let me know if you have any issue implementing the same.
回答2:
Try this code for without Key or tag..
try {
JSONArray itemArray=new JSONArray(jsonString);
for (int i = 0; i < itemArray.length(); i++) {
String value = itemArray.getString(i);
Log.e("json", value);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
来源:https://stackoverflow.com/questions/38769107/how-to-get-the-json-array-from-the-json-object