How to use JSON output in java - 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

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 find a value within a JSONObject/Array Lookup

Below is the JSON feed:
{
"list" : {
"meta" : {
"type" : "resource-list",
"start" : 0,
"count" : 2
},
"resources" : [
{
"resource" : {
"classname" : "Quote",
"fields" : {
"name" : "USD/KRW",
"price" : "1151.295044",
"symbol" : "KRW=X",
"ts" : "1437357550",
"type" : "currency",
"utctime" : "2015-07-20T01:59:10+0000",
"volume" : "0"
}
}
}
,
{
"resource" : {
"classname" : "Quote",
"fields" : {
"name" : "SILVER 1 OZ 999 NY",
"price" : "0.067476",
"symbol" : "XAG=X",
"ts" : "1437169614",
"type" : "currency",
"utctime" : "2015-07-17T21:46:54+0000",
"volume" : "62"
}
}
}
,
{
"resource" : {
"classname" : "Quote",
"fields" : {
"name" : "USD/VND",
"price" : "21815.500000",
"symbol" : "VND=X",
"ts" : "1437357540",
"type" : "currency",
"utctime" : "2015-07-20T01:59:00+0000",
"volume" : "0"
}
}
}
]
}
}
How do I go about finding the "price" of the JSON object who's symbol is ("symbol" : "XAG=X") for example. In this case the answer is ("price" : "0.067476"). I need to perform this lookup programatically since the JSON is rather larger than the one presented here and the only parameter given to me will be the "symbol".
Is this possible? Any detailed help on how to do this would be greatly appreciated.
This is your Json object Format
Try this for getting correct result -
JSONObject list = new JSONObject(content).getJSONObject("list");
JSONArray resources = list.getJSONArray("resources");
for (int j = 0; j < resources.length(); j++) {
JSONObject resource = resources.getJSONObject(j).getJSONObject("resource");
JSONObject fields = resource.getJSONObject("fields");
if(fields.getString("symbol").equals("XAG=X")){
System.out.println("Price of symbol(XAG=X) is"+ fields.getString("price"));
}
}
Assuming content represents the json string
import org.json.JSONArray;
import org.json.JSONObject;
JSONObject list = new JSONObject(content).getJSONObject("list");
JSONArray resources = list.getJSONArray("resources");
for (int j = 0; j < resources.length(); j++) {
JSONObject resource = resources.getJSONObject(j).getJSONObject("resource");
JSONObject fields = resource.getJSONObject("fields");
System.out.println(fields.get("symbol"));
System.out.println(fields.get("price"));
}

Java query for mongodb to find documents where list size is less than n

I'm trying to find all of the documents in my db where the the size of my "states" list only contains one state but I'm struggling with the syntax of the java code.
My db looks like this:
{ "_id" : 13218 , "country" : { "MY" : 11 , "US" : 4} , "state" : { "WA" : 4 }}
{ "_id" : 95529 , "country" : { "US" : 6 } , "state" : { "MI" : 6 }}
{ "_id" : 22897 , "country" : { "US" : 4 } , "state" : { "CA" : 2 , "TX" : 1 , "WY" : 1 }}
What I want to do is print out every "_id" found from the US that only has a single state. So, the only "_id" that'd be returned here is 95529.
here is the relevant portion of code:
DBObject query = new BasicDBObject("country.US", new BasicDBObject("$gt", 4));
//query.put("state.2", new BasicDBObject("$exists", true));
//This is my attempt at checking the list length but it doesn't work
DBCursor dbCursor = dBcollection.find(query);
while (dbCursor.hasNext()){
DBObject record = dbCursor.next();
Object _id= record.get("_id");
Object state= record.get("state");
System.out.println(_id + "," + state);
}
current output looks like this:
95529, { "MI" : 6 }
22897, { "CA" : 2 , "TX" : 1 , "WY" : 1 }
The essential problem you have here is that your data is not in fact a "list". As a "hash" or "map" which is what it really is there is no concept of "length" in a MongoDB sense.
You would be better off changing your data to use actual "arrays" which is what a list actually is:
{
"_id" : 13218 ,
"country" : [
{ "code": "MY", "value" : 11 },
{ "code": "US", "value" : 4 },
],
"state" : [{ "code": "WA", "value" : 4 }]
},
{
"_id" : 95529 ,
"country" : [{ "code": "US", "value" : 6 }],
"state" : [{ "code": "MI", "value" : 6 }]
},
{
"_id" : 22897 ,
"country" : [{ "code": "US", "value" : 4 }],
"state" : [
{ "code": "CA", "value" : 2 },
{ "code": "TX", "value" : 1 },
{ "code": "WY", "value" : 1 }
]
}
Then getting those documents that only have a single state is a simple matter of using the $size operator.
DObject query = new BasicDBObject("country",
new BasicDBObject( "$elemMatch", new BasicDBObject(
"code", "US").put( "value", new BasicDBObject( "$gt", 4 )
)
);
query.put( "state": new BasicDBObject( "$size", 1 ) );
This ultimately gives you a lot more flexibilty in issuing queries as you don't need to specify the explicit "key" in each query. Also as noted, there is a concept of length here that does not otherwise exist.
If you keep your data in it's current form then the only way to do this is with the JavaScript evaluation of the $where operator. That is not very efficient as the interpreted code needs to be run for each document in order to determine if the condition matches:
DBObject query = new BasicDBObject("country.US", new BasicDBObject("$gt", 4));
query.put("state", new BasicDBObject( "$type", 3 ));
query.put("$where","return Object.keys( this.state ).length === 1");
Also using the $type operator in order to make sure that "state" is actually present and an "Object" that is expected. So possible, but not a really great idea do to performance.
Try to change your document structure as it will make other sorts of queries possible without using JavaScript evaluation.

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");
}
}

google distance matrix api strange

I am facing a strange problem here,
when I run below url from web browser or from java command line
http://maps.googleapis.com/maps/api/distancematrix/json?origins=416%2063,Sweden&destinations=424%2069,Stor%C3%A5s%20Industrigatan%2020,Angered,G%C3%B6teborg&sensor=false
I get below results.
{
"destination_addresses" : [ "StorĂ¥s Industrigata 20, 424 69
Angered, Sweden" ],
"origin_addresses" : [ "Gothenburg, Sweden" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "10.4 km",
"value" : 10388
},
"duration" : {
"text" : "15 mins",
"value" : 924
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
but when I run the same url from glassfish server I mean sending an
http request from
form submit I get below strange response
{ "destination_addresses" : [ "" ],
"origin_addresses" : [ "Gothenburg, Sweden" ],
"rows" : [
{
"elements" : [
{
"status" : "NOT_FOUND"
}
]
}
],
"status" : "OK"
}
please not destination_addresses is empty in this case and status in
NOT_FOUND.
Java code I used to get the response is
private String getResponse(String URL) throws Exception {
InputStream stream = new URL(URL).openStream();
byte[] array = new byte[stream.available()];
stream.read(array);
return new String(array);
}
please guide me to resolve this issue,
thanks....
Use https
unless google will not let your software to connect.
and
get a api key.
read this:
https://developers.google.com/maps/documentation/distance-matrix/start
https://maps.googleapis.com/maps/api/distancematrix/json?origins=416%2063,Sweden&destinations=424%2069,Stor%C3%A5s%20Industrigatan%2020,Angered,G%C3%B6teborg&sensor=false&key=YOUR_API_KEY
be sure to replace YOUR_API_KEY with your actual API key
I had a similar problem when using the Distance Matrix API in Java. Setting the language in my request seems to make it work:
DistanceMatrixElement distanceMatrixElement;
DistanceMatrix matrix;
try
{
matrix = distanceMatrixApiRequest
.origins(...)
.destinations(...)
.language("en")
.await();
}

Categories

Resources