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

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:

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();
}
`

org.json.JSONException: No value for Name JSON extraction error

I am getting this error when I try to get the value for "Name" out of the following JSON:
{
"edges": [
{
"node": {
"Name": "Sunday River",
"Latitude": 44.4672,
"Longitude": 70.8472
}
},
{
"node": {
"Name": "Sugarloaf Mountain",
"Latitude": 45.0314,
"Longitude": 70.3131
}
}
]
}
This is the snippet of code I am using to try and access these values, but I am just testing getting "Name" for now:
String[] nodes = stringBuilder.toString().split("edges");
nodes[1] = "{" + "\"" + "edges" + nodes[1];
String s = nodes[1].substring(0,nodes[1].length()-3);
Log.d(TAG, s);
JSONObject json = new JSONObject(s);
JSONArray jsonArray = json.getJSONArray("edges");
ArrayList<String> allNames = new ArrayList<String>();
ArrayList<String> allLats = new ArrayList<String>();
ArrayList<String> allLongs = new ArrayList<String>();
for (int i=0; i<jsonArray.length(); i++) {
JSONObject node = jsonArray.getJSONObject(i);
Log.d(TAG, node.toString(1));
String name = node.getString("Name");
Log.d(TAG, name);
}
My output looks like this:
{"edges":[{"node":{"Name":"Sunday River","Latitude":44.4672,"Longitude":70.8472}},{"node":{"Name":"Sugarloaf Mountain","Latitude":45.0314,"Longitude":70.3131}}]}}
{
"node": {
"Name": "Sunday River",
"Latitude": 44.4672,
"Longitude": 70.8472
}
}
org.json.JSONException: No value for Name
I understand that I could use optString and not get the error, but that will not give me the data stored in each node.
Here is a version that works with your unaltered JSON:
public static void main(String... args)
{
String json = "{\"data\":{\"viewer\":{\"allMountains\":{\"edges\":[{\"node\":{\"Name\":\"Sunday River\",\"Latitude\":44.4672,\"Longitude\":70.8472}},{\"node\":{\"Name\":\"Sugarloaf Mountain\",\"Latitude\":45.0314,\"Longitude\":70.3131}}]}}}}";
JSONObject obj = new JSONObject(json);
JSONObject data = obj.getJSONObject("data");
JSONObject viewer = data.getJSONObject("viewer");
JSONObject allMountains = viewer.getJSONObject("allMountains");
// 'edges' is an array
JSONArray edges = allMountains.getJSONArray("edges");
for (Object edge : edges) {
// each of the elements of the 'edge' array are objects
// with one property named 'node', so we need to extract that
JSONObject node = ((JSONObject) edge).getJSONObject("node");
// then we can access the 'node' object's 'Name' property
System.out.println(node.getString("Name"));
}
}

Parsing and retrieving elements in a JSON 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 :)

How to properly convert java object to Json (Nested)

Okay so the output I would like to get is this:
{
"id": 460,
"position": {
"x": 3078,
"y": 3251,
"z": 0
},
"random-walk": true,
"walk-radius": 1
},
But the one I currently get is:
{
"id": 460,
"position": "{
"x": 3078,
"y": 3251,
"z": 0
}",
"random-walk": true,
"walk-radius": 0
},
The problem is the position object that I am trying to convert to json.
The code I tried:
Path path = Paths.get("./npcs.json");
File file = path.toFile();
file.getParentFile().setWritable(true);
if (!file.getParentFile().exists()) {
try {
file.getParentFile().mkdirs();
} catch (SecurityException e) {
System.out.println("Unable to create directory for donator data!");
}
}
try (FileWriter writer = new FileWriter(file)) {
Gson builder = new GsonBuilder().setPrettyPrinting().create();
JsonObject object = new JsonObject();
Position pos = new Position(mob.absX, mob.absY, mob.heightLevel);
object.addProperty("id", mob.npcId);
object.addProperty("position", builder.toJson(pos));
object.addProperty("random-walk", mob.randomWalk);
object.addProperty("walk-radius", mob.walkingType);
writer.write(builder.toJson(object));
writer.close();
} catch (Exception e) {
System.out.println("Something went wrong with saving for mob !");
e.printStackTrace();
}
Does anyone has a clue on how to get the first result? So without the double-quotes.
Use this
object.add("position", new Gson().toJsonTree(pos));
instead of
object.addProperty("position", builder.toJson(pos));
result should than look like this:
"position": {
"x": 10,
"y": 50
},
JSONObject json = new JSONObject();
JSONArray addresses = new JSONArray();
JSONObject address;
try
{
int count = 15;
for (int i=0 ; i<count ; i++)
{
address = new JSONObject();
address.put("Name","Name no." + i);
address.put("Country", "Country no." + i);
addresses.put(address);
}
json.put("Addresses", addresses);
}
catch (JSONException jse)
{
out.println("Error during json formatting" + jse.getMessage());
}
I would recommend using a JSONObject for your main JSON. After that, add each of the components. For a vector, add a json array. Here is a simple example I used to understand this better.
You can use your own java objects to be precise. Gson accesses the fields in your class using reflection, so you won't have to parse anything manually.
For example in your case:
import com.google.gson.annotations.SerializedName;
public class Walk {
private int id;
private Position position;
#SerializedName("random-walk")
private boolean randomWalk;
#SerializedName("walk-radius")
private int walkRadius;
}
public class Position {
private int x,y,z;
}
Then use
Gson gson = new Gson();
Walk walk = gson.fromJson(yourJson, Walk.class);

Categories