How to get the json array from the json object?

隐身守侯 提交于 2021-02-10 06:24:29

问题


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

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