Parsing JSON File Java [duplicate] - java

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 5 years ago.
I want to parse a JSON file in java and get the following values from the file mentioned below:
{
"status": "OK",
"origin_addresses": [ "Vancouver, BC, Canada", "Seattle, État de Washington, États-Unis" ],
"destination_addresses": [ "San Francisco, Californie, États-Unis", "Victoria, BC, Canada" ],
"rows": [ {
"elements": [ {
"status": "OK",
"duration": {
"value": 340110,
"text": "3 jours 22 heures"
},
"distance": {
"value": 1734542,
"text": "1 735 km"
}
}, {
"status": "OK",
"duration": {
"value": 24487,
"text": "6 heures 48 minutes"
},
"distance": {
"value": 129324,
"text": "129 km"
}
} ]
}, {
"elements": [ {
"status": "OK",
"duration": {
"value": 288834,
"text": "3 jours 8 heures"
},
"distance": {
"value": 1489604,
"text": "1 490 km"
}
}, {
"status": "OK",
"duration": {
"value": 14388,
"text": "4 heures 0 minutes"
},
"distance": {
"value": 135822,
"text": "136 km"
}
} ]
} ]
}
From every element, i want to get the value field of both distance and duration. How do i do this?

Using the json.org reference implementation (org.json homepage, Download here). The code is a bit messy but I think it does what you are asking for. You can take alot of shortcuts by not creating all this objects but to access them directly. The reason that I do it this way is an attempt to make it easier to follow whats happening.
package com.mypackage;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
String jsonStr = "{\"status\": \"OK\",\"origin_addresses\": [ \"Vancouver, BC, Canada\", \"Seattle, État de Washington, États-Unis\" ],\"destination_addresses\": [ \"San Francisco, Californie, États-Unis\", \"Victoria, BC, Canada\" ],\"rows\": [ {\"elements\": [ {\"status\": \"OK\",\"duration\": {\"value\": 340110,\"text\": \"3 jours 22 heures\"},\"distance\": {\"value\": 1734542,\"text\": \"1 735 km\"}}, {\"status\": \"OK\",\"duration\": {\"value\": 24487,\"text\": \"6 heures 48 minutes\"},\"distance\": {\"value\": 129324,\"text\": \"129 km\"}} ]}, {\"elements\": [ {\"status\": \"OK\",\"duration\": {\"value\": 288834,\"text\": \"3 jours 8 heures\"},\"distance\": {\"value\": 1489604,\"text\": \"1 490 km\"}}, {\"status\": \"OK\",\"duration\": {\"value\": 14388,\"text\": \"4 heures 0 minutes\"},\"distance\": {\"value\": 135822,\"text\": \"136 km\"}} ]} ]}";
try {
JSONObject rootObject = new JSONObject(jsonStr); // Parse the JSON to a JSONObject
JSONArray rows = rootObject.getJSONArray("rows"); // Get all JSONArray rows
for(int i=0; i < rows.length(); i++) { // Loop over each each row
JSONObject row = rows.getJSONObject(i); // Get row object
JSONArray elements = row.getJSONArray("elements"); // Get all elements for each row as an array
for(int j=0; j < elements.length(); j++) { // Iterate each element in the elements array
JSONObject element = elements.getJSONObject(j); // Get the element object
JSONObject duration = element.getJSONObject("duration"); // Get duration sub object
JSONObject distance = element.getJSONObject("distance"); // Get distance sub object
System.out.println("Duration: " + duration.getInt("value")); // Print int value
System.out.println("Distance: " + distance.getInt("value")); // Print int value
}
}
} catch (JSONException e) {
// JSON Parsing error
e.printStackTrace();
}
}
}

Create an class structure that reflects the JSON
Use a library like Jackson or GSON to deserialize the json to instances of your classes.
If you want a more dynamic approach, the above frameworks can also serialize to maps.

Use a library for working with JSON. For example google-gson.

as Bozho said create class structure that reflacts JSON and then use jacson library as follow:
refer Parsing JSON File Java
ObjectMapper mapper = new ObjectMapper();
Projects projs =
mapper.readValue(new File("projects.json"),Projects.class);
ArrayList<Project> projects = projs.get("projects");
for (Project p : projects) {
ArrayList<String> description = p.getDescription();
for (String s : description) {
System.out.println(s);

You can use a library like JSON-java
import org.json.JSONObject;
String jsonString = ...
JSONObject object = new JSONObject(jsonString);
String status = object.getString("status");

You can use :
org.bson.Document d = org.bson.Document.parse("{ foo: \"bar\" }");

yes you can use jacson to parse it but there is more easy way to do it
its Jsonme lib "import org.json.me" you dont have to add jar file to use it
JSONObject obj = new JSONObject("{'var1':'val1','var2':200});
String var1=obj.getString("var1");
int var2=obj.getInt("var2");
yes its more easy but if your project is complex i advice you to use jacson lib

Related

JSON object is getting removed with remove method in JSON file instead of JSON array [duplicate]

This question already has answers here:
How to remove an element from JSON string in Java?
(2 answers)
Closed 6 months ago.
I am trying to remove JSON array from a JSON file using org.json library
I am trying to remove webAutomation JSON array from the JSON file as follows
{
"instructor": "Test_Instructor",
"url": "www.google.com",
"services": "Test Automation Service",
"expertise": "Testing",
"linkedIn": "linkedIn",
"courses": {
"webAutomation": [
{
"price": "500",
"courseTitle": "Selenium"
},
{
"price": "333",
"courseTitle": "Protractor"
}
],
"apiAutomation": [
{
"price": "344.00",
"courseTitle": "Rest Assured API Automation"
}
],
"mobileAutomation": [
{
"price": "4555",
"courseTitle": "Appium"
}
]
}
}
I tried following code. Here str has JSON file
JSONObject jsonObject = new JSONObject(str);
jsonObject.getJSONObject("courses").getJSONArray("webAutomation");
System.out.println("after removal");
String str2 = mapper.writeValueAsString(jsonObject);
System.out.println(str2);
This is removing the whole JSON object instead of just JSON Array.
The output is {"empty":false}
Please help
You can use remove method in org.json.JSONObject#remove.
JSONObject json = new JSONObject(str);
json.getJSONObject("courses").remove("webAutomation");
System.out.println(json);
The output will be:
{
"instructor": "Test_Instructor",
"url": "www.google.com",
"services": "Test Automation Service",
"expertise": "Testing",
"linkedIn": "linkedIn",
"courses": {
"apiAutomation": [
{
"price": "344.00",
"courseTitle": "Rest Assured API Automation"
}
],
"mobileAutomation": [
{
"price": "4555",
"courseTitle": "Appium"
}
]
}
}

What is the best way to extract data from this JSON string? [duplicate]

I have some trouble with parsing a JSON response. The response data:
{
"deal": {
"categorie": {
"description": "Offres Shopping",
"idcategorie": "1",
"nom": "Shopping"
},
"conditions": "2 personne au plus",
"dateAjout": "2013-01-07T00:00:00+01:00",
"dateExp": "2013-01-31T00:00:00+01:00",
"description": "nuit dans un hotel 5 etoile",
"heurexp": "12",
"iddeal": "1",
"minutesexp": "30",
"prestataire": {
"adresse": "Qu zohour 44",
"codePostale": "12600",
"description": "Hotel 5 etoiles",
"idprestataire": "1",
"nom": "Hotel ronald",
"pays": "France",
"telephone": "99999999",
"ville": "Brest"
},
"prix": "80.0",
"prixHabituel": "200.0",
"tags": "hotel",
"titre": "Nuit 5 etoiles"
}
}
When trying to parse this response to a List<Deal> I get this exception:
com.google.gson.JsonObject cannot be cast to com.google.gson.JsonArray
This is the code that I am using for the parse:
if (reponse != null && !reponse.isEmpty()) {
System.out.println(reponse);
Gson g = new Gson();
JsonParser parser = new JsonParser();
JsonObject jObject = parser.parse(reponse).getAsJsonObject();
JsonArray jArray = jObject.getAsJsonArray("deal"); // here goes the Exception
for (JsonElement elem : dealArray) {
deals.add(g.fromJson(elem, Deal.class));
}
System.out.println(deals.toString());
return "success";
}
thanks
Well, deal is not a JSON array, its a JSON object. Hence the exception. A JSON array, for reference, would look more like this:
"deal" : [{"attr" : "value"}, {"attr" : "value"}]

The sum of several items in a json

I have a JSON source with more empty_slots elements (in the example exist below only one, but in the reality exist more stations with empty_slots). How can I sum the values from empty_slots and return as double? Thanks!
JAVA
public static double getValueFromJSONString(String jString) throws JSONException
{
JSONObject json = new JSONObject(jString);
return json.getJSONObject("empty_bikes").getDouble(jString);
}
JSON
{"network": {
"company": [
"Gewista Werbegesellschaft m.b.H"
],
"id": "citybike-wien",
"location": {
"city": "Wien",
},
"stations": [
{
"empty_slots": 3,
"extra": {
"slots": "26",
},
"free_bikes": 23
}]}
Checkout JsonPath. Below code is not tested but should work with RestAssured dependency - https://github.com/rest-assured/rest-assured
JsonPath jsonPath = new JsonPath(jsonString);
List<Integer> companyEntityIds = jsonPath.getList("network.stations.empty_slots");
Once you have the array you can just use a stream or whatever to add these up.

Parsing Chrome Bookmarks Json file : Java

Currently I am using netbeans IDE. I tried using other solution, but to no luck so far.
Problem is, i am facing errors when trying to read the Json file from google Chrome bookmarks file (C:\Users\Admin\AppData\Local\Google\Chrome\User Data\Default\Bookmarks)
p/s: although there is no file type written in the name of Bookmarks, its content have been known as JSON
This is the what inside the Bookmarks.json:
{
"checksum": "20fdfad51db6d3199f8a09c3220dd93b",
"roots": {
"bookmark_bar": {
"children": [ {
"date_added": "13124893413824227",
"id": "6",
"name": "YouTube",
"type": "url",
"url": "https://www.youtube.com/"
}, {
"date_added": "13124893435163243",
"id": "7",
"name": "Welcome to Facebook",
"type": "url",
"url": "https://www.facebook.com/"
} ],
"date_added": "13124893381424539",
"date_modified": "13124893435163243",
"id": "1",
"name": "Bookmarks bar",
"type": "folder"
},
"other": {
"children": [ ],
"date_added": "13124893381424547",
"date_modified": "0",
"id": "2",
"name": "Other bookmarks",
"type": "folder"
},
"synced": {
"children": [ ],
"date_added": "13124893381424550",
"date_modified": "0",
"id": "3",
"name": "Mobile bookmarks",
"type": "folder"
}
},
"version": 1
}
And here is my code (JsonParser.java):
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JsonParser{
private static String jsonFile = "C:\\Users\\Admin\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Bookmarks";
public static void main (String[] args) {
try {
FileReader reader = new FileReader (jsonFile); //access the file
JSONObject jsonObject = (JSONObject) new JSONParser().parse(reader);
String c =(String) jsonObject.get("checksum"); //place
// String r =(String) jsonObject.get("roots"); //place
// String r =(String) jsonObject.get("children"); //place
System.out.println("check: " + c);
//System.out.println("roots: " + r);
JSONArray lang = (JSONArray) jsonObject.get("roots");
for (int i=0; i<lang.size(); i++) {
System.out.println ("Url Name : " + lang.get(i)+"\n");
} //data in the array
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
For some reason when I run the code these are the errors I got:
check: 4d55f8a0888f7dd918a702eda2821ccd
Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray
at JsonParser.main(JsonParser.java:28)
C:\Users\Admin\Documents\NetBeansProjects\Keep-It\nbproject\build-impl.xml:1051: The following error occurred while executing this line:
C:\Users\Admin\Documents\NetBeansProjects\Keep-It\nbproject\build-impl.xml:805: Java returned: 1
BUILD FAILED (total time: 2 seconds)
As you can see, only checksum succeed in being read, but the roots failed and gave out these errors.
You should also notice that there are some codes I put as comments, those are things i tried but still got the errors.
I hope anyone can help me to get these things working.
Thank you very much for helping
Issue is , you cannot cast object to array like (JSONArray) jsonObject.get("roots"); you have to follow the structure so parse according to object and array as shown below
JSONObject jsonObject = (JSONObject) new JSONParser().parse(reader);
String checksum =jsonObject.optString("checksum");
// get root object
JSONObject root = jsonObject.getJSONObject("roots");
// get root bookmarks object from root
JSONObject bookmarks = root.getJSONObject("bookmark_bar");
// get root children array from bookmarks
JSONArray childrens = bookmarks.getJSONArray("children");
JSONObject temp ;
for (int i=0; i<childrens.size(); i++) {
// get object using index from childrens array
temp = childrens.getJSONObject(i);
// get url
String url = temp.optString("url");
}
as your structure follow
JObject => root
root JSONObject has : bookmark_bar JSONObject
bookmark_bar JSONObject has : children JSONArray
children JSONArray has JSONObject which further has String: url
roots is not a JSONArray but a JSONObject.
So what you have to do is
JSONObject lang = jsonObject.get("roots");
and then you have too loop through all keys in the object which should be:
bookmark_bar
other
synced
It seems to me like "roots" is not an array, but an object when looking at the JSON. "children" under "bookmark_bar" is an array however

Unable to get specific data from a JSON object

I am trying to extract specific data from a json response using org.json.JSONObject library
Heres is my json response :
{
"facets": {
"application": [
{
"name": "38",
"distribution": 1
}
],
"node": [
{
"name": "frstlwardu03_05",
"distribution": 1
}
],
"area": [
{
"name": "x",
"distribution": 1
}
],
"company": [
{
"name": "war001",
"distribution": 1
}
]
},
"duObjects": [
{
"id": "TASK|TSK(ZRM760J)(000)(ZRM760JU00)(000)|ZSRPSRM000",
"name": "TSK(ZRM760J)(000)(ZRM760JU00)(000)",
"mu": "ZSRPSRM000",
"label": "",
"session": "ZRM760J|000",
"sessionLabel": "SAP SRM Achats frais generaux execution",
"uprocHeader": "ZRM760JU00|000",
"uprocHeaderLabel": "Header for SRM760J",
"uprocHeaderType": "CL_INT",
"domain": "M",
"domainLabel": "",
"application": "38",
"applicationLabel": "magasin",
"highlightResult": {
"name": "name",
"word": "TSK"
}
}
],
"totalCount": 1,
"pageSize": 10,
"pageCurrent": 1,
"pageNb": 1
}
Here is the method I used to convert the URL call to a jsonobject :
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException
{
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-
8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
When I call this method I am able to get the data in teh Duobject :
public static void main(String[] args) throws IOException, JSONException {
JSONObject json = readJsonFromUrl("http://frstmwarwebsrv.orsyptst.com:9000/duobject?
searchString=TSK(ZRM760J)(000)(ZRM760JU00)
(000)&filterchecks=nameJob,nameWF,nameSWF,application,domain&p.index=0&p.size=10");
System.out.println(json.getJSONArray("duObjects"));
}
Is there anyway I can extract only the name field of the DuObjects?
You can use
System.out.println(json.getJSONArray("duObjects").getJSONObject(0).getString("name"));
to get the name.
1 : your complete response is a JSON OBJECT
2 : if any element is written like
"some key name " : { " some value " }
this is a JSON Object
3 : if any element is writen like
"some key name " : " some value "
this is value inside you json object which you can get by
jsonObject.getString("key name")
4 : if any element is writen like
"some key name " : [ " some value " ]
then this is a JSON Array and you have to take it in to a JSON ARRAY and then traverse its elements by
jsonObject.getJSONARRAY("key name for JSON ARRAY IN RESPONSE ")
and then you can traverse the elements of the JSON ARRAY by
`jsonArrayObj.get(0);`
You can use Jackson libraries to covert to java. Jackson api provides annotation level and it automatically converts json to pojo object and object to json vice versa . refer this link. you can get good idea about this
http://wiki.fasterxml.com/JacksonSampleSimplePojoMapper
http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/

Categories

Resources