how I can get data from JSONObject with Java? - 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
}

Related

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

Get value out JSON Object containing JSON arrays

How can I get the value of "distance" out of the following JSON object with java?
{
"destination_addresses" : [ "New York City, New York, Verenigde Staten" ],
"origin_addresses" : [ "Washington D.C., District of Columbia, Verenigde Staten" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "225 mijl",
"value" : 361714
},
"duration" : {
"text" : "3 uur 51 min.",
"value" : 13877
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
I tried:
json.getJSONArray("rows").getJSONObject(0).getJSONObject("distance").toString();
But I always get org.json.JSONException: JSONObject["distance"] not found.
I think you are missing the second array "elements", you find array "row" so get object 0, in object 0 you need to find the "elements" array then take the object 0 again, so you can get the "distance" object.
Try this:
json.getJSONArray("rows").getJSONObject(0).getJSONArray("elements").getJSONObject(0).getJSONObject("distance").toString();
Again, I think. I hope this helped you.
Use java-json.jar
Convert JSON String to object and fetch the element.
You can refer this.
Try this:
package Sample;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class TestMain
{
public static void main(String[] args) throws JSONException
{
String s="{ \"destination_addresses\" : [ \"New York City, New York, Verenigde Staten\" ], \"origin_addresses\" : [ \"Washington D.C., District of Columbia, Verenigde Staten\" ], \"rows\" : [ { \"elements\" : [ { \"distance\" : { \"text\" : \"225 mijl\", \"value\" : 361714 }, \"duration\" : { \"text\" : \"3 uur 51 min.\", \"value\" : 13877 }, \"status\" : \"OK\" } ] } ], \"status\" : \"OK\"} ";
JSONObject jsonObj = new JSONObject(s);
JSONArray array= (JSONArray) jsonObj.get("rows");
JSONObject jsonObj2 =(JSONObject) array.get(0);
JSONArray array2= (JSONArray)jsonObj2.get("elements");
JSONObject jsonObj3 =(JSONObject) array2.get(0);
System.out.println(jsonObj3.get("distance"));
}
}
OUTPUT:
{"text":"225 mijl","value":361714}

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

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 ...
}
]

How to use JSON output in java

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

How to decode this nested JSON string?

i tried many times to decode nested JSON string which consist of nested Array , i used GSON() to do that. and it's worked , but the problem is about objects inside this array don't be decoded from json, so i want your help :
JSON String :
{ "data" : { "current_condition" : [ { "cloudcover" : "75",
"humidity" : "87",
"observation_time" : "03:16 AM",
"precipMM" : "1.5",
"pressure" : "991",
"temp_C" : "11",
"temp_F" : "52",
"visibility" : "7",
"weatherCode" : "293",
"weatherDesc" : [ { "value" : "Patchy light rain" } ],
"weatherIconUrl" : [ { "value" : "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0033_cloudy_with_light_rain_night.png" } ],
"winddir16Point" : "SSW",
"winddirDegree" : "210",
"windspeedKmph" : "30",
"windspeedMiles" : "19"
} ],
"request" : [ { "query" : "London, United Kingdom",
"type" : "City"
} ],
"weather" : [ { "date" : "2014-01-03",
"precipMM" : "6.9",
"tempMaxC" : "10",
"tempMaxF" : "50",
"tempMinC" : "5",
"tempMinF" : "41",
"weatherCode" : "293",
"weatherDesc" : [ { "value" : "Patchy light rain" } ],
"weatherIconUrl" : [ { "value" : "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0017_cloudy_with_light_rain.png" } ],
"winddir16Point" : "SW",
"winddirDegree" : "220",
"winddirection" : "SW",
"windspeedKmph" : "33",
"windspeedMiles" : "21"
} ]
} }
my Code to decode this JSON :
HashMap HashMap = new Gson().fromJson(json, HashMap.class);
and it's output :
{data={request=[{query=London, United Kingdom, type=City}],
current_condition=[{cloudcover=75, humidity=87, observation_time=03:16
AM, precipMM=1.5, pressure=991, temp_C=11, temp_F=52, visibility=7,
weatherCode=293, weatherDesc=[{value=Patchy light rain}],
weatherIconUrl=[{value=http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0033_cloudy_with_light_rain_night.png}],
winddir16Point=SSW, winddirDegree=210, windspeedKmph=30,
windspeedMiles=19}], weather=[{date=2014-01-03, precipMM=6.9,
tempMaxC=10, tempMaxF=50, tempMinC=5, tempMinF=41, weatherCode=293,
weatherDesc=[{value=Patchy light rain}],
weatherIconUrl=[{value=http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0017_cloudy_with_light_rain.png}],
winddir16Point=SW, winddirDegree=220, winddirection=SW,
windspeedKmph=33, windspeedMiles=21}]}}
so i want an ideal method to give me ability to enter this nested HashMap array and it's values , because my method don't give me ability to call nested values from this array
Thank you ,
as the string represents a Hashmap inside another Hashmap you can use some thing like,
HashMap<String, HashMap> hashMap = new Gson().fromJson(json, HashMap.class);
It's worked after i did this method :
Type type = new TypeToken< HashMap<String, HashMap<String, ArrayList<com.google.gson.internal.LinkedTreeMap>>>>() {}.getType();
HashMap<String, HashMap<String, ArrayList<com.google.gson.internal.LinkedTreeMap>>> hashMap = new Gson().fromJson(API.getJSON(), type);
com.google.gson.internal.LinkedTreeMap hash = hashMap.get("data").get("current_condition").get(0);
System.out.println(" "+hash.get("humidity")+" ");
i know that your answers and my first method are true , but as i told you that i want to enter the entry nested array list inside this Json

Categories

Resources