Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get jsonarray key name [duplicate]

Tags:

java

json

android

I need to get a key name of JsonArray, so JSON looks like this, please not, that JSON is starting with array brackets, and inside it it has objects, that was made i guess because back end will have the ability to add objects.

[
  {
    "tehnology": [ ]
  },
  {
    "science": []
  }
]

So i need to get the names from it "technology" and "science", because json can dynamically change, how can I implement it?

like image 204
k.nadonenko Avatar asked May 23 '15 12:05

k.nadonenko


People also ask

Can we have duplicate key in JSON?

JSON with duplicate key entries have to be handled either by ignoring the duplicate entries or by throwing an exception. Until Mule Runtimes 3.8. 6/3.9. 0, JSON Schema Validator handles them by retaining the last duplicate entry and not throwing an exception.

Can JSON have multiple keys with same name?

There is no "error" if you use more than one key with the same name, but in JSON, the last key with the same name is the one that is going to be used. In your case, the key "name" would be better to contain an array as it's value, instead of having a number of keys "name".

Can Yaml have duplicate keys?

Duplicate keys in YAML files are not allowed in the spec (https://yaml.org/spec/1.2.2/#nodes, https://yaml.org/spec/1.0/#model-node), but the older version of symfony/yaml does not complain about them. The newer version throws an exception.

Can JSON have multiple keys?

What is key and value in JSON? A JSON object contains zero, one, or more key-value pairs, also called properties. The object is surrounded by curly braces {} . Every key-value pair is separated by a comma.


1 Answers

The JSONArray contains JSONObjects. Retrieve every JSONObject and use keys() to access the key defined in every JSONObject

 JSONArray jArray = new JSONArray(response);       
 for (int i = 0; i < jArray.length(); i++) {
      JSONObject object = jArray.optJSONObject(i);
      Iterator<String> iterator = object.keys();
      while(iterator.hasNext()) {
        String currentKey = iterator.next();
      }
 }
like image 154
Blackbelt Avatar answered Oct 27 '22 00:10

Blackbelt