Read JsonElement from Json file? - java

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

Related

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

Error on reading json file using JSON Simple Library

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

Removing simple object from JSON request

I wrote a small code to validate that my request fails when some part of it is removed.I want to remove the product element and its value.
Here's the request
{
"product": "tv",
"price": "45",
"payment": {
"credit_card": {
"number": "1234567891234567",
"type": "Visa",
"expire_month": 10,
"expire_year": 2019,
"cvv2": 999,
"first_name": "John",
"last_name": "Smith"
}
}
}
This is the code snippet -
JSONParser parser = new JSONParser();
String requestFile = System.getProperty("user.dir") + "/src/test/resources/request/request.json";
logger.info("Loading request file: " + requestFile);
Object obj = parser.parse(new FileReader(requestFile));
JSONObject jsonObject = (JSONObject) obj;
//fails on the below line saying Java.lang.String cannot be cast to org.json.simple.JSONObject
// What's the alternative?
logger.info("printing json object "+jsonObject.get("product"));
jsonObject = (JSONObject) jsonObject.remove("product");
System.out.println("Now the request is "+jsonObject);
I was able to resolve this problem.
Here's the code snippet after making changes in it.
JSONParser parser = new JSONParser();
String requestFile = System.getProperty("user.dir") + "/src/test/resources/request/original_request.json";
logger.info("Loading request file: " + requestFile);
Object obj = parser.parse(new FileReader(requestFile));
Object jsonObject = (JSONObject) obj;
//remove product_name
((HashMap) jsonObject).remove("product");
logger.info("New request "+jsonObject);

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