Java JSONObject get children - java

i want to create gmaps on my website.
I found, how to get coordinates.
{
"results" : [
{
// body
"formatted_address" : "PuĊ‚awska, Piaseczno, Polska",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 52.0979041,
"lng" : 21.0293984
},
"southwest" : {
"lat" : 52.0749265,
"lng" : 21.0145743
}
},
"location" : {
"lat" : 52.0860667,
"lng" : 21.0205308
},
"location_type" : "GEOMETRIC_CENTER",
"viewport" : {
"northeast" : {
"lat" : 52.0979041,
"lng" : 21.0293984
},
"southwest" : {
"lat" : 52.0749265,
"lng" : 21.0145743
}
}
},
"partial_match" : true,
"types" : [ "route" ]
}
],
"status" : "OK"
}
I want to get:
"location" : {
"lat" : 52.0860667,
"lng" : 21.0205308
},
From this Json.
I decided to user json-simple
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1</version>
</dependency>
My code is:
String coordinates = //JSON from google
JSONObject json = (JSONObject)new JSONParser().parse(coordinates);
And i can get the first children: "results"
String json2 = json.get("results").toString();
json2 display correct body of "results"
But i cannot get "location" children.
How to do it ?
Thanks

I think you need to cast the call to json.get("results") to a JSONArray.
I.e.
String coordinates = //JSON from google
JSONObject json = (JSONObject)new JSONParser().parse(coordinates);
JSONArray results = (JSONArray) json.get("results");
JSONObject resultObject = (JSONObject) results.get(0);
JSONObject location = (JSONObject) resultObject.get("location");
String lat = location.get("lat").toString();
String lng = location.get("lng").toString()
The trick is to look at what type the part of the json you're deserializing is and cast it to the appropriate type.

about this link
com.google.gson.JsonParser#parse(java.lang.String) is now deprecated
so use com.google.gson.JsonParser#parseString, it works pretty well
Kotlin Example:
val mJsonObject = JsonParser.parseString(myStringJsonbject).asJsonObject
Java Example:
JsonObject mJsonObject = JsonParser.parseString(myStringJsonbject).getAsJsonObject();

Related

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
}

How to get the Content from Specific Field from JSONObject Data

i want to get from this JSONObject Data , the content of field "_source",
JSONObject jsonObj =
{
"hits" : [
{
"_index" : "try1",
"_type" : "_doc",
"_id" : "1",
"_score" : 1.0,
"_source" : {
"target" : {
"br_id" : 0,
"wo_id" : 2,
"process" : [
"element 1",
"element 2"
]
},
"explanation" : {
"an_id" : 1311,
"pa_name" : "micha"
},
"text" : "hello world"
}
}
]
}
the Result should be like bellow ,
String result =
{
"target" : {
"br_id" : 0,
"wo_id" : 2,
"process" : [
"element 1",
"element 2"
]
},
"explanation" : {
"an_id" : 1311,
"pa_name" : "micha"
},
"text" : "hello world"
}
I tried this , but it always could not recognize the "_source" field,
JSONObject main = jsonObj.getJSONObject("hits");
JSONObject content = main.getJSONObject("_source");
JSONObject field = content.getJSONObject("target");
JSONObject["_source"] not found
JSONObject["target"] not found
Please any suggestion or Advices, so i can get the Content from "_source" as Result?
thx.
_source is inside of JSONArray hits, so first get the JSONArray
JSONArray main = jsonObj.getJSONArray("hits");
And then get the first JSONObject from array
JSONObject obj = main.getJSONObject(0);
JSONObject source = obj.getJSONObject("_source"); //now get the _source

I have a json string and I can't extract specific field

I Have a json String that looks like this:
{
"results" : [
{
"address_components" : [
{
"long_name" : "Arad",
"short_name" : "Arad",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Arad",
"short_name" : "Arad",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Arad County",
"short_name" : "AR",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "Romania",
"short_name" : "RO",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "Arad, Romania",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 46.2217118,
"lng" : 21.3823449
},
"southwest" : {
"lat" : 46.1286902,
"lng" : 21.230371
}
},
"location" : {
"lat" : 46.1865606,
"lng" : 21.3122677
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 46.2217118,
"lng" : 21.3823449
},
"southwest" : {
"lat" : 46.1286902,
"lng" : 21.230371
}
}
},
"place_id" : "ChIJw1lco0uYRUcRkYRVPkoHcA8",
"types" : [ "locality", "political" ]
}
],
"status" : "OK"
}
My java code:
jsonString = readUrl("https://maps.googleapis.com/")
rootNode = objectMapper.readTree(jsonString);
JsonNode resultsNode = rootNode.path("results");
JsonNode addressNode = resultsNode.path("address_components");
JsonNode geometryNode = addressNode.path("geometry");
JsonNode locationNode = geometryNode.path("location");
JsonNode latNode = locationNode.path("lat");
JsonNode lngNode = locationNode.path("lng");
System.out.println(latNode.asDouble());
System.out.println(lngNode.asDouble());
The last 2 line print 0.0 and 0.0. How can I obtain lat and lng information from this json?
p.s I diden't post the full url link.
Maybe the jsonNodes are not correct but I can't find the solution.
The problem is that results is not an object but an array of objects. You have to choose element by index. The proper solution is:
jsonString = readUrl("https://maps.googleapis.com/")
rootNode = objectMapper.readTree(jsonString);
JsonNode resultsNode = rootNode.path("results");
JsonNode addressNode = resultsNode.get(0); //selecting first json object from an array
JsonNode geometryNode = addressNode.path("geometry");
JsonNode locationNode = geometryNode.path("location");
JsonNode latNode = locationNode.path("lat");
JsonNode lngNode = locationNode.path("lng");
System.out.println(latNode.asDouble());
System.out.println(lngNode.asDouble());
You may also want to iterate all objects in results, in that case code, which will print coordinates of each object, should be:
jsonString = readUrl("https://maps.googleapis.com/")
rootNode = objectMapper.readTree(jsonString);
JsonNode resultsNode = rootNode.path("results");
Iterator<JsonNode> results = resultsNode.elements();
while(results.hasNext()){
JsonNode addressNode = results.next();
JsonNode geometryNode = addressNode.path("geometry");
JsonNode locationNode = geometryNode.path("location");
JsonNode latNode = locationNode.path("lat");
JsonNode lngNode = locationNode.path("lng");
System.out.println(latNode.asDouble());
System.out.println(lngNode.asDouble());
}

Android: How do I get the following JSON Object?

I am trying to get the latitude and longitudes items from the location in a JSON but I am getting an array out of bounds exception on Android.
Here is the JSON file:
{
"results" : [
{
"address_components" : [
{
"long_name" : "21211",
"short_name" : "21211",
"types" : [ "postal_code" ]
},
{
"long_name" : "Baltimore",
"short_name" : "Balt",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Maryland",
"short_name" : "MD",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "Baltimore, MD 21211, USA",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 39.3476939,
"lng" : -76.619315
},
"southwest" : {
"lat" : 39.310951,
"lng" : -76.65690289999999
}
},
"location" : {
"lat" : 39.3289463,
"lng" : -76.63838319999999
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 39.3476939,
"lng" : -76.619315
},
"southwest" : {
"lat" : 39.310951,
"lng" : -76.65690289999999
}
}
},
"place_id" : "ChIJn-Z5WtQEyIkRQx9CtdQF7-I",
"types" : [ "postal_code" ]
}
],
"status" : "OK"
}
I just need the two attributes:
"location" : {
"lat" : 39.3289463,
"lng" : -76.63838319999999
}
I tried doing this but no luck:
JSONObject jObj = new JSONObject(jData);
JSONArray results = jObj.getJSONArray("results");
JSONObject geometry = results.getJSONObject(2); //ERROR RIGHT HERE!
JSONObject location = geometry.getJSONObject("location");
Double latitude = location.getDouble("lat");
Double longitude = location.getDouble("lng");
You should get JSONObject geometry = results.getJSONObject(0); because there is only one object in the array. However, if I were you, I'd create an ArrayList and use for(int i = 0; i < results.size(); i++) to get every object in case of coming more than one object, doing something like:
JSONObject jObj = new JSONObject(jData);
JSONArray results = jObj.getJSONArray("results");
ArrayList<LocationObject> _locationList = new ArrayList<>();
for(int i = 0; i < results.size(); i++){
JSONObject geometry = results.getJSONObject(i).getJSONObject("geometry");
JSONObject location = geometry.getJSONObject("location");
LocationObject _locationObject = new LocationObject();
_locationObject.setLat(location.getDouble("lat"));
_locationObject.setLng(location.getDouble("lng"));
_locationObject.add(_locationObject);
}
You cannot get your geomettry as you did,since there is no object at with the index 2 in your json object.
I think you have not formatted well your json responce.
Copy past your responce in this web site and you ll understand.
and here is some code:
JSONObject tmp = results.getJSONObject(0);
JSONObject geometery = tmp.getJSONObject ("geometery");

Android - How to parse JSONObject and JSONArrays

My build is Android 2.2 Google API 8 , Im running from the emulator. I am trying try access Location long in this JSON Object. I get this after I use
InputStream instream = entity.getContent();
JSONObject myAwway = new JSONObject(convertStreamToString(instream));
Google docs says it returns an array but with the surrounding curly braces It looks like an object.
I need to access lat and lon in the location field and store as doubles.
Ive searched but only seem to find help with simple files.
{
"results" : [
{
"address_components" : [
{
"long_name" : "20059",
"short_name" : "20059",
"types" : [ "postal_code" ]
},
{
"long_name" : "Washington D.C.",
"short_name" : "Washington D.C.",
"types" : [ "locality", "political" ]
},
{
"long_name" : "District of Columbia",
"short_name" : "DC",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "Washington D.C., DC 20059, USA",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 38.924920,
"lng" : -77.0178720
},
"southwest" : {
"lat" : 38.9189910,
"lng" : -77.02261200000001
}
},
"location" : {
"lat" : 38.92177780,
"lng" : -77.01974260
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 38.92510312068017,
"lng" : -77.01709437931984
},
"southwest" : {
"lat" : 38.91880787931983,
"lng" : -77.02338962068018
}
}
},
"types" : [ "postal_code" ]
}
],
"status" : "OK"
}
JSONObject jObject = new JSONObject(convertStreamToString(instream));
JSONArray results = jObject.getJSONArray("result");
JSONObject geometry = results.getJSONObject(2);
JSONObject bounds = geometry.getJSONObject("bounds");
JSONObject northeast = geometry.getJSONObject("northeast");
double nLat = Double.parseDouble(northeast.getString("lat").toString());
double nLng = Double.parseDouble(northeast.getString("lng").toString());
That should give you lat/lng for northeast as doubles. Southeast is the same just replace northeast for southeast.
JSONObject location = myAwway.getJSONArray("results").getJSONObject(0).getJSONObject("geometry").getJSONObject("location");
double lat = location.getDouble("lat");
double lng = location.getDouble("lng");
The 'results' JSONArray is probably the array Google docs suggested. They had just wrapped it up in a JSONObject with a status, so that you could check the status before attempting to work on the returned value.

Categories

Resources