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");
}
}
Related
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
}
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!!!
I have a JSONfile like :
{ "data" :
{ "stop1" : [ "elem1", "elem2", "elem3", "elem4"],
"stop2" : [ "selem1", "selem2", "selem3", "selem4"]
}
}
For parsing this file I have written the following code:-
HashMap<String, String> stopList = new HashMap<>();
JSONObject dataJsonObj = (new JSONObject(json)).getJSONObject("data");
JSONArray busStopJsonObj, urlJsonObj;
busStopJsonObj = dataJsonObj .getJSONArray("stop1");
urlJsonObj = dataJsonObj .getJSONArray("stop2");
for (int i = 0; i < busStopJsonObj.length(); i++)
stopList.put(busStopJsonObj.getString(i), urlJsonObj.getString(i));
However i get an error as:
org.json.JSONException: Value {"stop1":["elem1","elem2"
org.json.JSON.typeMismatch(JSON.java:100)
org.json.JSONArray.getJSONArray(JSONArray.java:500)
Seems like your JSON is invalid. The correct JSON should be:
{"data": {
"stop1": [
"elem1",
"elem2",
"elem3",
"elem4"
],
"stop2": [
"selem1",
"selem2",
"selem3",
"selem4"
]
}
}
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 ...
}
]
I am making a program which gets the Json distance matrix from Google Maps API. So far i wrote the program can get the json it looks as below
{
"destination_addresses" : [
"Paris, France",
"Toulon, France",
"Nantes, France",
"Marseille, France"
],
"origin_addresses" : [
"Paris, France",
"Toulon, France",
"Nantes, France",
"Marseille, France"
],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "1 m",
"value" : 0
},
"duration" : {
"text" : "1 min",
"value" : 0
},
"status" : "OK"
},
{
"distance" : {
"text" : "839 km",
"value" : 838906
},
"duration" : {
"text" : "7 hours 21 mins",
"value" : 26476
},
"status" : "OK"
},
{
"distance" : {
"text" : "384 km",
"value" : 384421
},
"duration" : {
"text" : "3 hours 34 mins",
"value" : 12823
},
"status" : "OK"
},
{
"distance" : {
"text" : "774 km",
"value" : 774398
},
"duration" : {
"text" : "6 hours 48 mins",
"value" : 24490
},
"status" : "OK"
}
]
},
Now what i want to do is to create a distance matrix as this
[ Paris Toulon Nantes Marseille ]
[Paris 0 838906 384421 774398 ]
[Toulon value 0 value value]
[Nantes value value 0 value]
[Marseille value value value 0 ]
** The values stands for distance between the cities.
(in java form of course) and later i will use it in solving the TSP. I need the values from Elements --> Distance --> Values. Any help would be appreciated. Thanks in advance.
You can use org.codehaus.jettison.json.JSONArray for the same (Download jar).
Example Code :
JSONObject json = new JSONObject(result_string);
JSONArray rows = json .getJSONArray("rows");
Creating distance matrix for TCP problem :
You can use the following code :
JSONObject json1 = new JSONObject(json);
String places[] ={"Paris" , "Toulon" , "Nantes" , "Marseille" };
String[][] result=new String[places.length][places.length];
JSONArray rows = json1.getJSONArray("rows");
//JSONObject[] elements=new JSONObject[places.length];
for (int i = 0; i < rows.length(); i++) {
JSONObject obj=rows.getJSONObject(i);
JSONArray elements=obj.getJSONArray("elements");
for (int j = 0; j < elements.length(); j++) {
JSONObject elem=elements.getJSONObject(j);
JSONObject distance = elem.getJSONObject("distance");
result[i][j]=distance.getString("value");
}
}
for (int i = 0; i < result.length; i++) {
String row[]=result[i];
for (int j = 0; j < row.length; j++) {
System.out.print(" " +row[j] + " , ");
}
System.out.println();
}
Like this you can get values of json string .
When working with JSON we usually use libraries to make it easier, someone else has done the hard work to parse all that information.
GSON is one https://code.google.com/p/google-gson/ and there are plenty others if you look around.
Once you have a library, give it your json and then you can start manipulating it. You will be able to get rows -> element -> duration -> text quite easily.
This should get your started: http://www.javacreed.com/simple-gson-example/
From there you should write code to take your GSON and put in a datas tructure that makes it easy to work with like a binary tree or something similar.
Remember libraries are your friend.
you can use Java Api for JSON.
you can start with : http://www.oracle.com/technetwork/articles/java/json-1973242.html
download and install "json.simple".
add maven dependency in pom.xml file.
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1</version>
</dependency>
You can also refer this site