Error on reading json file using JSON Simple Library - java

I am trying to read the following JSON file in java.
Here is my JSON File
{
"names": [
{
"no": 1,
"name": "John"
},
{
"no": 2,
"name": "Paul"
}
],
"new_names": [
{
"no": 11,
"name": "John"
},
{
"no": 12,
"name": "Paul"
}
]
}
Java Code:
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class ReadFile {
#SuppressWarnings("unchecked")
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader(
"D://data.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray nameList = (JSONArray) jsonObject.get("names");
System.out.println("\nnames:");
Iterator<String> iterator = nameList.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I want to print names array, but I am getting following error:
java.lang.ClassCastException: org.json.simple.JSONObject cannot be
cast to java.lang.String at ReadFile.main(ReadFile.java:34)

Your JSonArray nameList has has JSONObjects inside, not the strings,
You should do replace your String with JSONObject as mentioned in Exception trace
Iterator<JSONObject > iterator = nameList.iterator();
while (iterator.hasNext()) {
JSONObject jsonObjct= iterator.next()
System.out.println(jsonObjct.getInt("no"));
System.out.println(jsonObjct.getString("name"));
}

Iteratoring from JsonObject..
So you should change below:
Iterator<String> iterator = nameList.iterator();
to following:
Iterator<JSONObject> iterator = nameList.iterator();
And iterate it using for loop, Iterator won't work for JSONArray.

It is this line that is causing the problem:
Iterator<String> iterator = nameList.iterator();
Try using the following instead:
arrLength = nameList.Length()
for (int i = 0; i < arrLength; ++i) {
JSONObject jsonObj = nameList.getJSONObject(i);
System.out.println(jsonObj)
}

Related

Read multiple json array with different names dynamically

I have a JSON which has many arrays with a different name, just like below JSON.
{
"CA": [
{
"high": 5,
"low": 3,
"key": "ABPS"
},
{
"high": 6,
"low": 2,
"key": "ABPO"
}
],
"EE": [
{
"high": 8,
"low": 4,
"key": "ABPS"
},
{
"high": 7,
"low": 2,
"key": "ABPO"
}
]
}
I am trying to iterate JSON array values dynamically without specifying the name of the array.
I am able to read array with specifying the name of the array with below code but how to read array values dynamically without specifying the name of every array because the JSON file I have it has thousands of array.
package com.abc;
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 JsonRead {
private static final String filePath = "jsonTestFile.json";
public static void main(String[] args) {
try (FileReader reader = new FileReader(ClassLoader.getSystemResource(filePath).getFile())) {
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
// get an array from the JSON object
JSONArray lang = (JSONArray) jsonObject.get("CA");
Iterator i = lang.iterator();
// take each value from the json array separately
while (i.hasNext()) {
JSONObject innerObj = (JSONObject) i.next();
System.out.println("high " + innerObj.get("high") + " low " + innerObj.get("low")+ " key " + innerObj.get("key"));
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
This might help
for (Iterator iterator = jsonObject.keySet().iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
JSONArray jArray = (JSONArray) jsonObject.get(key);
}

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 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:

Read JsonElement from Json file?

I need to read JsonElements from given JSON files. I am using org.json.simple jar.
Here is the sample of my json:
[{
"Submission ID": "9938306",
"Lat": "17.447191666666665",
"Long": "78.38849"
},
{
"Submission ID": "9938306",
"Lat": "17.447191666666665",
"Long": "78.38849"
}]
I wrote this following code to read JsonArray but not able to figure out how to read JsonElements from it:
try {
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("sampleData.json"));
JSONArray array = (JSONArray) obj;
Iterator iter = array.iterator();
while (iter.hasNext()){
}
}
How can I read all JSONelements for each JSONarray? For example:
EDIT
I want to iterate all JsonElements in JsonAray. In my given Json I do have submission ID and submission_ID. Key is dynamic in some point and I need to read it and want to apply some regex on it.
running code. try it
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class Test {
public static void main(String[] args) throws FileNotFoundException, IOException, ParseException {
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("/home/stpl/NIKHIL/text.json"));
JSONArray array = (JSONArray) obj;
for(int i = 0; i < array.size(); i++)
{
JSONObject objects = (JSONObject)array.get(i);
System.out.println(objects.get("Submission ID")+" "+objects.get("Lat")+" "+objects.get("Long"));
}
}
}
my text.json
[{
"Submission ID": "9938306",
"Lat": "17.447191666666665",
"Long": "78.38849"
},
{
"Submission ID": "9938306",
"Lat": "17.447191666666665",
"Long": "78.38849"
}]
You should use Jackson ? Which provides good utilities to parse JSON file.
You can try this code :
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("d://sample.json"));
JSONArray array = (JSONArray) obj;
Iterator iter = array.iterator();
while (iter.hasNext()) {
JSONObject json = (JSONObject) iter.next();
Iterator<String> keys = json.keySet().iterator();
while (keys.hasNext()) {
String key = keys.next();
System.out.println("Key :" + key + " Value :" + json.get(key));
}
}
This will iterate each key and value of given JSON.
Please try following code,
try {
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("sampleData.json"));
JSONArray array = (JSONArray) obj;
for(int i=0;i<array.length();i++){
JSONObject obj=array.getJSONObject(i);
System.out.println(obj.get("Long"));
}
}
Note:not compiled

Categories