Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get value from JSONObject without mention its name?

My JSONObject:

{MyJSON:[{"id":"1","name":"panji","price":"100"}]}

I do this to get value of id:

menuitemArray.getJSONObject(i).getString("id");

Can I get the value of id, name or price, without mentioning its name, may be like index or another method?

like image 804
panji Avatar asked May 05 '12 06:05

panji


People also ask

How do you get a specific value from a JSON String?

getJsonString() Method It is used to get the (JsonString)get(name). The method parses an argument name of type String whose related value is to be returned. It returns the String value of the associated mapping for the parsed parameter. It returns null if the object has no mapping for the parameter.

How do you check the type of a value from a JSONObject?

A JSONObject has few important methods to display the values of different types like getString() method to get the string associated with a key string, getInt() method to get the int value associated with a key, getDouble() method to get the double value associated with a key and getBoolean() method to get the boolean ...

Can JSONObject be null?

JSONObject. NULL is equivalent to the value that JavaScript calls null, whilst Java's null is equivalent to the value that JavaScript calls undefined.

How do I know if a JSONObject has a key?

Use below code to find key is exist or not in JsonObject . has("key") method is used to find keys in JsonObject . If you are using optString("key") method to get String value then don't worry about keys are existing or not in the JsonObject . Note that you can check only root keys with has(). Get values with get().


3 Answers

You can call names() on a JSONObject to get a JSONArray of the names of its elements - this would let you do logic on them or retrieve their corresponding values dynamically.

like image 171
Paul Bellora Avatar answered Sep 29 '22 01:09

Paul Bellora


You can get all the attributes of a JSONObject like this

for(Iteraor key=jsonObject.keys();itr.hasNext();) {
   jsonObject.get(key.next());
}
like image 33
gkamal Avatar answered Sep 29 '22 02:09

gkamal


JSONObject obj = new JSONObject(json);
for(Iterator<String> keys=obj.keys();keys.hasNext();) {
    obj.get(keys.next());
}
like image 20
Ziad Alzarka Avatar answered Sep 29 '22 02:09

Ziad Alzarka