简体   繁体   中英

How to get the json array from the json object?

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 text array 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

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.

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM