jsonArray.length() not given the right number of array element - java

I am using org.json parser.
I am getting a json array using jsonObject.getJSONArray(key).
The problem is the jsonArray.length() is returning me 1 and my json array have 2 elements, what am I doing wrong?
String key= "contextResponses";
JSONObject jsonObject = new JSONObject(jsonInput);
Object value = jsonObject.get("contextResponses");
if (value instanceof JSONArray){
JSONArray jsonArray = (JSONArray) jsonObject.getJSONArray(key);
System.out.println("array length is: "+jsonArray.length());/*the result is 1! */
}
Here is my json:
{
"contextResponses" : [
{
"contextElement" : {
"type" : "ENTITY",
"isPattern" : "false",
"id" : "ENTITY3",
"attributes" : [
{
"name" : "ATTR1",
"type" : "float",
"value" : ""
}
]
},
"statusCode" : {
"code" : "200",
"reasonPhrase" : "OK"
}
}
]
}

The result is perfectly normal, since the JSONArray contains only one JSONObject. To get the length of the JSONObject you're looking for, use this:
// Get the number of keys stored within the first JSONObject of this JSONArray
jsonArray.getJSONObject(0).length();
//----------------------------
{
"contextResponses" : [
// The first & only JSONObject of this JSONArray
{
// 2 JSONObjects
"contextElement" : {
// 1
},
"statusCode" : {
// 2
}
}
]
}

Your array contains exactly one object therefore the length is correct:
"contextResponses" : [
{
... content of the object ...
}
]

Related

Check if Json Array is empty or contains one Json Object

How can I check whether
{
"data": [
{
"latitude": 12,
"longitude": 13
}
]
}
contains one object, as the previous example, or it is empty, as the following example:
{
"data": [
[]
]
}
This is my snippet:
...
JSONObject jsonObject = new JSONObject(response.body());
JSONArray jsonArray = jsonObject.getJSONArray("data");
...
You can check the data array length like this:
if(jsonArray.length() > 0) { //it means that there is a record in data attr }

how I can get data from JSONObject with Java?

I have an String called inputJson that contains
{"listPruebas": [
{
"nombrePrueba" : "pruebaA",
"id" : 1,
"tipoPrueba" : "PRUEBABASE1",
"elementoBase" : "tipoA",
"listaMarca": [
{
"elemento": "elemento1 ",
"tipo": "ABC",
"cadena": "SFSG34235WF32"
},
{
"elemento":"elemento2",
"tipo":"DEF",
"cadena":"DJRT64353GSDG"
},
{
"elemento" : "elemento3",
"formato ":"JPG"
}
]},
{
"nombrePrueba" : "pruebaB",
"id" : 2,
"tipoPrueba" : "PRUEBABASE2",
"elementoBase" : "imagenPrueba",
"listaMarca2": [
{
"elemento" : "imagen",
"tipo": "tipo5",
"cadena": "iVBORw0KGgoAAAANSUhEUgAAAgAAAA"
}
]
}
],
"listaBuscar":
[
{
"tipoBusqueda":"busqueda1",
"id" : 1,
"operacion" : "operacion1",
"valor" : "12"
},
{
"tipoBusqueda":"binario",
"id" : 2,
"operacion" : "operacion2",
"valor" : "13"
},
{
"tipoFiltro":"numerico",
"id" : 31,
"operacion" : "MENOR_QUE",
"valor" : "1980",
"intervalo" : 1
}
]
}
and I converted the String to JSONObject of this way
JSONObject object = new JSONObject(inputJson);
and I got this
jsonObject::{"listaBuscar":[{"valor":"12","id":1,"operacion":"operacion1","tipoBusqueda":"busqueda1"},{"valor":"13","id":2,"operacion":"operacion2","tipoBusqueda":"binario"},{"tipoFiltro":"numerico","intervalo":1,"valor":"1980","id":31,"operacion":"MENOR_QUE"}],"listPruebas":[{"listaMarca":[{"tipo":"ABC","elemento":"elemento1","cadena":"SFSG34235WF32"},{"tipo":"DEF","elemento":"elemento2","cadena":"DJRT64353GSDG"},{"elemento":"elemento3","formato":"JPG"}],"elementoBase":"tipoA","tipoPrueba":"PRUEBABASE1","nombrePrueba":"pruebaA","id":1},{"elementoBase":"imagenPrueba","tipoPrueba":"PRUEBABASE2","listaMarca2":[{"tipo":"tipo5","elemento":"imagen","cadena":"iVBORw0KGgoAAAANSUhEUgAAAgAAAA"}],"nombrePrueba":"pruebaB","id":2}]}
and now I need to extract information but I dont know how to do, for example I try this
object.getString("elemento1");
but I got this error
Caused by: org.json.JONException: JSONObject["elemento1"] not found
help me please
You can't get a nest JSON object from the top level. It's like a treemap. You need to convert it into a java object or get it level by level.
check this post, a lot of ways.
You json contains two json arrays, fetch them as -
JSONArray listaBuscArray = jsonObj.getJSONArray("listaBuscar");
JSONArray listPruebasArray = jsonObj.getJSONArray("listPruebas");
Now you can process and use them as -
for(int i=0; i<listaBuscArray.length; i++){
JSONObject obj = listaBuscArray.getJSONObject(i);
.... your logic
}

value doesn't exists while reading JSON

My JSON
{
"destination_addresses" : [
"11/6, Dhandapani St, VGP Seethapathy Nagar, Velachery, Chennai, Tamil Nadu 600042, India"
],
"origin_addresses" : [ "Magazine Road, St Thomas Mount, Chennai, Tamil Nadu 600016, India" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "6.6 km",
"value" : 6589
},
"duration" : {
"text" : "21 mins",
"value" : 1268
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
I need to get the distance value from this JSON.
I am getting value till rows but I get exception while I try to convert this JSON object to JSON Array.
Success till this
JSONArray rows= (JSONArray) jsonObject.get("rows");
JSONObject elements= (JSONObject) rows.get(0);
Log.d("Eleemnrs",String.valueOf(elements));
And when I execute below code there is no value for distance
JSONArray rows= (JSONArray) jsonObject.get("rows");
JSONObject elements= (JSONObject) rows.get(0);
elements.get("distance");
Log.d("Eleemnrs",String.valueOf(elements));
JSONObject elements= (JSONObject) rows.get(0);
This result elements is:
{
"elements" : [
{
"distance" : {
"text" : "10.3 km",
"value" : 10320
},
"duration" : {
"text" : "20 mins",
"value" : 1178
},
"status" : "OK"
}
]
}
If you should get the distance value you should get("elements") first and then getJsonObject(0).get("distance")
You are not making use of the object when you did elements.get("distance")
JSONArray rows= (JSONArray) jsonObject.get("rows");
JSONObject elements= (JSONObject) rows.get(0);
//Here you are not assigning the distance object to any variable. It is simply discarded
elements.get("distance");
Log.d("Eleemnts",String.valueOf(elements));
You can modify your code as follows to get the distance object into a JsonObject and read the values you require from it.
JSONArray rows= (JSONArray) jsonObject.get("rows");
JSONObject elements= (JSONObject) rows.get(0);
JsonObject distance = elements.get("distance");
Log.d("Distance text is ", distance.getString("text"));
Log.d("Distance value is ", distance.getInt("value"));
JSONArray rows= (JSONArray) jsonObject.get("rows");
JSONObject elements= (JSONObject) rows.get(0);
JSONArray one= (JSONArray) elements.get("elements");
JSONObject two=(JSONObject)one.get(0);
JSONObject three=(JSONObject)two.get("distance");
int finalvalue= (int) three.get("value");
Carved out the answer!!!

Reading the array name itself (not its content) from JSON using java

I have a JSON like this -
result = [
{ "value1": [
{
"number" : "3",
"title" : "hello_world"
},
{
"number" : "2",
"title" : "hello_world"
}
]
},
{ "value2": [
{
"number" : "4",
"title" : "hello_world"
},
{
"number" : "5",
"title" : "hello_world"
}
]
}
]
I want to get result[0] i.e "value1" and result[1] i.e "value2".
Below is my code for parsing this Json -
JsonParser jsonParser = new JsonParser();
JsonArray resultArray = jsonParser.parse(result.getAsJsonArray("result"));
Above code is working fine and I am getting 2 Json arrays. Now for getting value1 I have written this code-
String v = resultArray.get(0).getAsJsonObject().get("value1").getAsString();
But this is not giving me value1 rather than its throwing error "java.lang.IllegalStateException". What I am doing wrong here?
Please note that I want to read array name of "value1" and "value2" itself as string and not its inside content.Means print line should print value1 as output.
Value1 is not String but rather a JsonArray,
when you call getAsString() method, it will throw Exception telling you the value is not of a String object.
few Options :
1- read the value as JsonArray then convert it to String using toString method:
String v = resultArray.get(0).getAsJsonObject().getAsJsonArray("value1").toString();
2- use toString method directly on JsonElement itself (return value of get("value1")
String v = resultArray.get(0).getAsJsonObject().get("value1").toString();
I normally use option one because it enforces the check.
EDIT:
After reading comment, basically what is required is to get all the keys of each JsonObject within each Object
you need to loop through the array and get all they entrySet().(not tested but should work)
for(JsonElement element : resultArray){
JsonObject next= element.getAsJsonObject();
for(Map.Entry<String,JsonElement> entry : next.entrySet()){
System.out.println(entry.getKey()); // <-- prints out value1 and value2
}
}

Using Json to access a specific attribute

Hello guys i'm reading a page that contain JSON objects with JAVA (Android)
Here is what the page contains :
{
"destination_addresses" : [ "Safi, Maroc" ],
"origin_addresses" : [ "Avenue Hassan II, Safi, Maroc" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "1,0 km",
"value" : 966
},
"duration" : {
"text" : "2 minutes",
"value" : 129
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
I know how to read from the page doing this
JSONObject jArray = new JSONObject(result);
String elements = jArray.getString("rows");
the elements string contain that :
[{"elements" : [{"distance" : {"text" : "1,0 km","value" : 966},"duration" : {"text" : "2 minutes","value" : 129},"status" : "OK"}]}]
But im trying to get the distance value which is "966"
Thx guys
So you are trying to access an entry from the array. See Tutorials or examples. This is basic stuff:
http://www.mkyong.com/java/json-simple-example-read-and-write-json/
You need to actually use a JSONArray (which subclasses JSONObject)
You might want to take a look at this link:
How to parse JSON in Android
But for your particular problem you want to call something like:
int value = jArray.getJSONObject("rows").getJSONObject("elements").getJSONArray("distance").getInteger("value");
Try this..
JSONObject jObj = new JSONObject(result);
JSONArray rows = jObj.getJSONArray("rows");
for(int i = 0; i < rows.length; i++){
JSONObject obj = rows.getJSONObject(i);
JSONArray elements = jObj.getJSONArray("elements");
for(int j = 0; j < elements.length; j++){
JSONObject Jobj = elements.getJSONObject(j);
JSONObject distance = Jobj.getJSONObject("distance");
int distance_value = distance.getInteger("value");
JSONObject duration = Jobj.getJSONObject("duration");
int duration_value = duration.getInteger("value");
}
}

Categories

Resources