Parsing and retrieving elements in a JSON Java - java

JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("C:/Users/dan/Documents/rental.txt"));
JSONObject jsonObject = (JSONObject) obj;
for(Iterator iterator = jsonObject.keySet().iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
System.out.println(jsonObject.get(key));
}
} catch (Exception e) {
e.printStackTrace();
}
Following is the JSON String:
{
"Search": {
"VehicleList": [
{
"sipp": "CDMR",
"name": "Ford Focus",
"price": 157.85,
"supplier": "Hertz",
"rating": 8.9
},
{
"sipp": "FVAR",
"name": "Ford Galaxy",
"price": 706.89,
"supplier": "Hertz",
"rating": 8.9
}
]
}
}
}
Hi, I can iterate over the whole JSON object with my code but right now I want to print out the name of a vehicle and the price of the vehicle individually. Any help would be appreciated, I am a beginner when it comes to working with JSON.

Your JSON is structured like this JsonObject -> JsonArray-> [JsonObject]
With that in mind you can access the name and price with this
Object obj = parser.parse(new FileReader("C:/Users/dan/Documents/rental.txt"));
JSONArray jsonArray = (JSONObject) obj.getJsonArray("VehicleList");
for(JSONObject jsonObject : jsonArray){
System.out.println(jsonObject.getString("name") + " " + jsonObject.getDouble("price"))
}
}
Depending on your import library it may deviate from the above but the concept is the same.

You need to iterate over the json. For example.
$.Search.VehicleList[0].price will give you [157.85]
$.Search.VehicleList[1].price will give you [706.89]
http://www.jsonquerytool.com/ will come handy for you :)

Related

Reading json file with multiple objects in java

I have written a program that reads a simple json file:
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
JSONArray a = (JSONArray) parser.parse(new FileReader("C:/Users/Zonoid/Desktop/EQ.json"));
for (Object o : a)
{
JSONObject obj = (JSONObject) o;
String city = (String) obj.get("CITY");
System.out.println("City : " + city);
String loc = (String) obj.get("LOCATION");
System.out.println("Location : " + loc);
long el = (Long) obj.get("E_LEVEL");
System.out.println("Emergency Level : " + el);
long depth = (Long) obj.get("DEPTH");
System.out.println("Depth : " + depth);
long i = (Long) obj.get("INTENSITY");
System.out.println("Intensity :"+i);
System.out.println("\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
with my json file being:
[{"CITY":"MUMBAI","LOCATION":"a" ,"E_LEVEL": 6,"DEPTH":10,"INTENSITY":5},
{"CITY":"MUMBAI","LOCATION":"b" ,"E_LEVEL": 8,"DEPTH":20,"INTENSITY":4},
{"CITY":"MUMBAI","LOCATION":"c" ,"E_LEVEL": 3,"DEPTH":13,"INTENSITY":5},
{"CITY":"MUMBAI","LOCATION":"d" ,"E_LEVEL": 6,"DEPTH":12,"INTENSITY":4},]
I am working on a project that deals with earthquake alerts and want to read their JSON files however I cannot import them in JSON Array. The file I want to import looks like this:
{
"type": "FeatureCollection",
"metadata": {
"generated": 1488472809000,
"url": "https:\/\/earthquake.usgs.gov\/earthquakes\/feed\/v1.0\/summary\/significant_week.geojson",
"title": "USGS Significant Earthquakes, Past Week",
"status": 200,
"api": "1.5.4",
"count": 2
},
"features": [
{
"type": "Feature",
"properties": {
"mag": 5.5,
"place": "42km WSW of Anchor Point, Alaska",
"time": 1488420690658,....
Please tell what changes should be made.
If you are trying to read from features only, first you need to read the whole file as an object. Then you can, read the array part in the following way:
Object object = parser.parse(new FileReader("C:/Users/Zonoid/Desktop/EQ.json"));
JSONObject jasonObject = (JSONObject) object;
JSONArray features = (JSONArray) jasonObject.get("features");

How to create multi level JSON data using JSONObject in servlet

I need to create JSON data like below,
{
"min": {
"week": "1",
"year": "2014"
},
"max": {
"week": "14",
"year": "2017"
}
}
But JSONObject accepts only "id","value" format.
So how can I create JSON data using JSONObject like mentioned above.
That is very easy, here is an example:
JSONObject min = new JSONObject();
min.put("week", "1");
min.put("year", "2014");
JSONObject max = new JSONObject();
max.put("week", "14");
max.put("year", "2017");
JSONObject json= new JSONObject();
stats.put("min", min);
stats.put("max", max);
System.out.println(json.toString());
Tested this in eclipse already for you.
`
String s = "{ \"min\": { \"week\": \"1\", \"year\": \"2014\" }, \"max\": { \"week\": \"14\", \"year\": \"2017\" } }";
JSONParser parser = new JSONParser();
try {
JSONObject json = (JSONObject) parser.parse(s);
System.out.println(json.get("min"));
// this will output
//{"week":"1","year":"2014"}
} catch (Exception e){
e.printStackTrace();
}
`

How to decode JSONObject

This question is related with my previous question
I can successfully get the String in json format from the URL to my spring controller
Now I have to decode it
so I did like the following
#RequestMapping("/saveName")
#ResponseBody
public String saveName(String acc)
{jsonObject = new JSONObject();
try
{
System.out.println(acc);
org.json.JSONObject convertJSON=new org.json.JSONObject(acc);
org.json.JSONObject newJSON = convertJSON.getJSONObject("nameservice");
System.out.println(newJSON.toString());
convertJSON = new org.json.JSONObject(newJSON.toString());
System.out.println(jsonObject.getString("id"));
}
catch(Exception e)
{
e.printStackTrace();jsonObject.accumulate("result", "Error Occured ");
}
return jsonObject.toString();
}
This is the JSON String { "nameservice": [ { "id": 7413, "name": "ask" }, { "id": 7414, "name": "josn" }, { "id": 7415, "name": "john" }, { "id": 7418, "name": "RjhjhjR" } ] }
When I run the code then I get the error
org.json.JSONException: JSONObject["nameservice"] is not a JSONObject.
What wrong I am doing?
It's not a JSONObject, it's a JSONArray
From your question:
{ "nameservice": [ { "id": 7413, "name": "ask" }, { "id": 7414, "name": "josn" }, { "id": 7415, "name": "john" }, { "id": 7418, "name": "RjhjhjR" } ] }
The [ after the nameservice key tells you it's an array. It'd need to be a { to indicate an object, but it isn't
So, change your code to use it as a JSONArray, then iterate over the contents of that to get the JSONObjects inside it, eg
JSONArray nameservice = convertJSON.getJSONArray("nameservice");
for (int i=0; i<nameservice.length(); i++) {
JSONObject details = nameservice.getJSONObject(i);
// process the object here, eg
System.out.println("ID is " + details.get("id"));
System.out.println("Name is " + details.get("name"));
}
See the JSONArray javadocs for more details
It seems you're trying to get a JSONObject when "nameservice" is an array of JSONObjects and not an object itself. You should try this:
JSONObject json = new JSONObject(acc);
JSONArray jsonarr = json.getJSONArray("nameservice");
for (int i = 0; i < jsonarr.length(); i++) {
JSONObject nameservice = jsonarr.getJSONObject(i);
String id = nameservice.getString("id");
String name = nameservice.getString("name");
}
I don't understand why you do it manualy if you already have Spring Framework.
Take a look at MappingJackson2HttpMessageConverter and configure your ServletDispatcher accordingly. Spring will automatically convert your objects to JSON string and vice versa.
After that your controller method will be looked like:
#RequestMapping("/saveName")
#ResponseBody
public Object saveName(#RequestBody SomeObject obj) {
SomeObject newObj = doSomething(obj);
return newObj;
}

How to read a JSON file using JSON.simple library?

I'm trying to parse a json file using json simple library but I'm having some trouble getting the code to parse the json file. I've done some searching but every example's json file is formatted differently from the one I'm using. I'm able to query the full json file, but I can't get a specific piece of information from my json file and add it to a list (the list turns up empty).
The json file in question (this is a snippet of the original file for simplicity's sake):
{
"status": "ok",
"count": "2",
"data":{
"1":{
"country": "U.S.A.",
"name": "Jeremy",
"id": 1
},
"3":{
"country": "U.K.",
"name": "Dell",
"id": 3
}
}
}
The code I've tried using:
List<String> list = new ArrayList<String>();
String json = myJSONFile; // myJSONFile is a place holder for the location of the file.
JSONObject jsonObject = (JSONObject) JSONValue.parse(json);
JSONObject data = (JSONObject) jsonObject.get("data");
for (int x = 0; y > data.size(); y++)
{
JSONObject id = (JSONObject) data.get(y + "");
list.add((String) id.get("name");
}
// Used to show if the list is empty or not.
JOptionPane.showMessageDialog(null, list);
As pointed out in the comments, you JSON isn't a valid one. You can try parsing it here.
The correct JSON appears to be:
{
"status": "ok",
"count": "2",
"data": {
"1": {
"country": "U.S.A.",
"name": "Jeremy",
"id": 1
},
"3": {
"country": "U.K.",
"name": "Jeremy",
"id": 3
}
}
}
A couple of errors in your code:
1) You are trying to parse the JSON file location without reading it. You need to first read the file containing JSON string
List<String> list = new ArrayList<String>();
String json = "..\\json.txt";
JSONParser parser = new JSONParser();
Object parsed = parser.parse(new FileReader(json));
JSONObject jsonObject = (JSONObject) parsed;
2) Your loop doesn't make much sense. Here you want to try and iterate over the keys returned by your JSONObject represented by data
JSONObject data = (JSONObject) jsonObject.get("data");
Iterator<?> keys = data.keySet().iterator();
while (keys.hasNext()) {
if (data.get(keys.next()) instanceof JSONObject) {
JSONObject id = (JSONObject) data.get(keys.next());
list.add((String) id.get("name"));
System.out.println("Yo => " + (String) id.get("name"));
}
}
Here is the full working sample, modify per your need to make it more generic and best practices:
public static void main(String... args) {
try {
List<String> list = new ArrayList<String>();
String json = "..\\json.txt"; //Location of your json file
JSONParser parser = new JSONParser();
Object parsed = parser.parse(new FileReader(json));
JSONObject jsonObject = (JSONObject) parsed;
JSONObject data = (JSONObject) jsonObject.get("data");
Iterator<?> keys = data.keySet().iterator();
while (keys.hasNext()) {
if (data.get(keys.next()) instanceof JSONObject) {
JSONObject id = (JSONObject) data.get(keys.next());
list.add((String) id.get("name"));
System.out.println("Yo => " + (String) id.get("name"));
}
}
// Used to show if the list is empty or not.
JOptionPane.showMessageDialog(null, list);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Output:

parse json rest response in java

I am trying to parse json output from neo4j in java as:
Object obj = parser.parse(new FileReader("D:\\neo4j.json"));
JSONArray json = (JSONArray) obj;
System.out.println(json.size());
for (int i = 0; i < json.size(); i++) {
JSONObject jsonObject = (JSONObject) json.get(i);
String data = (String);
jsonObject.get("outgoing_relationships");
String name = (String) jsonObject.get("name");
System.out.println(data);
System.out.println(name);
}
Can somebody help me to get values inside "data" element:
I have json output from neo4j as follows:
[{
"outgoing_relationships": "http://host1.in:7474/db/data/node/133/relationships/out",
"data": {
"MOTHERS_NAME": "PARVEEN BAGEM",
"MOBILE_NO": "9211573758",
"GENDER": "M",
"name": "MOHD",
"TEL_NO": "0120-",
"PINCODE": "110001"
},
"traverse": "http://host1.in:7474/db/data/node/133/traverse/{returnType}",
"all_typed_relationships": "http://host1.in:7474/db/data/node/133/relationships/all/{-list|&|types}",
"property": "http://host1.in:7474/db/data/node/133/properties/{key}",
"self": "http://host1.in:7474/db/data/node/133",
"properties": "http://lhost1.in:7474/db/data/node/133/properties",
"outgoing_typed_relationships": "http://host1.in:7474/db/data/node/133/relationships/out/{-list|&|types}",
"incoming_relationships": "http://host1.in:7474/db/data/node/133/relationships/in",
"extensions": {
},
"create_relationship": "http://host1.in:7474/db/data/node/133/relationships",
"paged_traverse": "http://host1.in:7474/db/data/node/133/paged/traverse/{returnType}{?pageSize,leaseTime}",
"all_relationships": "http://host1.in:7474/db/data/node/133/relationships/all",
"incoming_typed_relationships": "http://host1.in:7474/db/data/node/133/relationships/in/{-list|&|types}"
}]
Regards,
Jayendra
You can try following way. Inside the for loop get the data node as JSONObject. From that data node you can extract every property. I just extracted mother name from data.
JSONObject data = (JSONObject) jsonObject.get("data");
final String motherName = (String) data.get("MOTHERS_NAME");
What library are you using to parse JSON ? I'd recommend that you use Jackson
For eg: To get the data you read from the file in a Map, you can write a method like this.
#SuppressWarnings("rawtypes")
public static Map toMap(Object object) throws JsonProcessingException{ ObjectMapper mapper = new ObjectMapper();
return mapper.convertValue(object, Map.class);
}

Categories