Reading Json file with many json objects - java

I wish to read a json file with contents below in Java recursively. How can I achieve that?
{"preview":false,"result":{"TransactionType":"Mobile","TransactionID":"STSVSTFS7SVS3S","TransTime":"20181210171511"}}
{"preview":false,"result":{"TransactionType":"Mobile","TransactionID":"LKSNS6S2S7SVS3S","TransTime":"20181210171511"}}
{"preview":false,"result":{"TransactionType":"Mobile","TransactionID":"TSSKBDGD7SVS3S","TransTime":"20181210171511"}}
Here is my Java code except it only reads the first json
import com.brian.db.DBConnector;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
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 ReadJSONData {
private static final String filePath = "D:\\test\\c2b.json";
public static void main(String[] args) throws SQLException {
try {
// read the json file
FileReader reader = new FileReader(filePath);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
//System.out.println(jsonObject);
Object preview = jsonObject.get("preview");
System.out.println("Preview:"+preview);
JSONObject result = (JSONObject) jsonObject.get("result");
System.out.println("RESULT:"+result);
String transactionType = (String) result.get("TransactionType");
System.out.println("TransactionType:"+transactionType);
String transid = (String) result.get("TransID");
System.out.println("TransID:"+transid);
String transTime = (String) result.get("TransTime");
System.out.println("TransTime:"+ transTime);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ParseException ex) {
ex.printStackTrace();
} catch (NullPointerException ex) {
ex.printStackTrace();
}
}
}

Just iterate over the lines and parse each one separately:
public class ReadJSONData {
private static final String filePath = "D:\\test\\c2b.json";
public static void main(String[] args) throws SQLException {
JSONParser jsonParser = new JSONParser();
try (Stream<String> stream = Files.lines(Paths.get(filePath))) {
stream.forEach(line -> {
try {
JSONObject jsonObject = (JSONObject) jsonParser.parse(line);
…
} catch (Exception e) {
}
});
}
}
}

Related

A space in JSON value causes "unexpected token END OF FILE at position 11" exception when parsing in Java

When I use the parser from org.json.simple.parser.* I get an exception whenever one of the values in JSON contains a space. For example:
{"name":"Adam"}
would parse correctly, but
{"name":"Ad am"}
would cause "unexpected token END OF FILE at position 11" exception
Here is the code that I use to convert a JSON string into a JSONObject.
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(stringJSON);
Try to get through this below example and each value contains space except integer one and giving this example just because of you don't have shared your source code.
JSON File(personal_detail.json):
{
"name":"arif mustafa",
"age":26,
"address":["district is Korba","state is Chhattisgarh","country is India"]
}
Java source to read the JSON file format:
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 JSONExample {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("src/resources/personal_detail.json"));
JSONObject jsonObject = (JSONObject) obj;
System.out.println(jsonObject + "\n");
String name = (String) jsonObject.get("name");
System.out.println("name : " + name);
long age = (Long) jsonObject.get("age");
System.out.println("age : " + age);
//get Object loop array
JSONArray address = (JSONArray) jsonObject.get("address");
System.out.println("address is : ");
Iterator<String> iterator = address.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}

Reading a json file in Java

So I am having troubles with reading a Json file in Java.
It is a Json file with content in this format:
{
"_id": 2864071,
"name": "Neustadt",
"country": "DE",
"coord": {
"lon": 12.56667,
"lat": 52.400002
}
}
This is the code I am using:
package controllers;
#Named(value = "cityID")
#SessionScoped
public class getCityIDs implements Serializable {
public long getCityIDs(String name) {
//Read the json file
try {
FileReader reader = new FileReader(filePath);
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(reader);
// get a number from the JSON object
String travelName = (String) jsonObject.get("name");
if(travelName.equals(name)){
long id = (long) jsonObject.get("_id");
System.out.println(id);
return id;
} else {
System.out.println("else");
return 0;
}
} catch (FileNotFoundException ex) {
Logger.getLogger(getCityIDs.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException | ParseException ex) {
Logger.getLogger(getCityIDs.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("einde functie");
return 0;
// JSONObject jsonObject = (JSONObject) parser.parse(getClass().getResource("/json/city.list.json").toString());
}
public String test(){
return "hello world";
}
}
However, it gives me an error at this line:
JSONObject jsonObject = (JSONObject) parser.parse(reader);
being:
Severe: Unexpected token LEFT BRACE({) at position 88.
at org.json.simple.parser.JSONParser.parse(Unknown Source)
at org.json.simple.parser.JSONParser.parse(Unknown Source)
at controllers.getCityIDs.getCityIDs(getCityIDs.java:45)
For some reason it can't read the filepath? "Unknown source"?
I'm not sure what I'm doing wrong.
The method just returns a "0" when I call the method in another class, with as country name "Neustadt".
Basically all I want is for this function to return the ID for a certain city.
The names are stored in the Json, together with the ID.
Edit:
Ideally I want to be able to parse the JSON file, which is located inside the project.
I tried using .getClass().getResource("/path/to/json"); but that didn't work at all.
EDIT: FIXED
package controllers;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
#Named(value = "cityID")
#SessionScoped
public class getCityIDs implements Serializable{
JSONObject jsonObject;
public long getCityIDs(String name) {
try {
JSONParser parser = new JSONParser();
InputStream in = getClass().getResourceAsStream("/dataSteden/stedenNamen1.json");
try (BufferedReader br = new BufferedReader(new InputStreamReader(in))) {
String line;
while ((line = br.readLine()) != null) {
jsonObject = (JSONObject) parser.parse(line);
}
}
String travelName = (String) jsonObject.get("name");
System.out.println("stad: " +travelName);
System.out.println("testttt");
if(travelName.equals(name)){
long id = (long) jsonObject.get("_id");
System.out.println(id);
return id;
} else {
System.out.println("else");
return 5;
}
} catch (FileNotFoundException ex) {
Logger.getLogger(getCityIDs.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException | ParseException ex) {
Logger.getLogger(getCityIDs.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("einde functie");
return 0;
// JSONObject jsonObject = (JSONObject) parser.parse(getClass().getResource("/json/city.list.json").toString());
}
public String test(){
return "hello world";
}
}
Your data is line-delimited
{"_id":707860,"name":"Hurzuf","country":"UA","coord":{"lon":34.283333,"lat":44.549999}}
{"_id":519188,"name":"Novinki","country":"RU","coord":{"lon":37.666668,"lat":55.683334}}
{"_id":1283378,"name":"Gorkhā","country":"NP","coord":{"lon":84.633331,"lat":28}}
Therefore, you cannot throw the entire file into a JSONParser, you must read the file line-by-line and parse each line as a JSONObject, from which you can extract out the needed key-values.

How do I read from JSON File in Java? [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 7 years ago.
I've read some other questions about this, but they did not seem to help me.
As the title says, I want to know how to read from .json files using Java.
Eg. I want my program to read a boolean value. (That is what I want it to.)
I really hope you will be able to help me with this. I am able to use json-simple-1.1.1 if needed.
What I've found so far (That did not work):
String str = "Name";
JSONObject obj = new JSONObject();
String n = (String) obj.get("Name");
if (!n.equals("true")) {
} else
if (n.equals("true")) {
ButtonsShow = true;
} else if (n.equals("false")) {
ButtonsShow = false;
}
Click to view the .Json file
you try it:
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 JsonSimpleExample {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("c:\\test.json"));
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");
System.out.println(name);
long age = (Long) jsonObject.get("age");
System.out.println(age);
// loop array
JSONArray msg = (JSONArray) jsonObject.get("messages");
Iterator<String> iterator = msg.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}

error: non-static method get(Object) cannot be referenced from a static context

The code below shows:
JavaApplication1.java:34: error: non-static method get(Object) cannot be referenced from a static context
JSONArray cars = (JSONArray) JSONObject.get("cars");
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 JavaApplication1 {
#SuppressWarnings("unchecked")
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
JSONArray a = (JSONArray) parser.parse(new FileReader("C:/Users/Glambert/Dropbox/java/New folder/perfection/UPdate/json.txt"));
for (Object o : a)
{
JSONObject person = (JSONObject) o;
String name = (String) person.get("name");
System.out.println(name);
String city = (String) person.get("city");
System.out.println(city);
String job = (String) person.get("job");
System.out.println(job);
JSONArray cars = (JSONArray) JSONObject.get("cars");
for (Object c : cars)
{
System.out.println(c+"");
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Anyone has any idea why this is the case?
(by the way, this code was found online and I edited it to test run, so that I can create a new code to take in a different kind of txt file.)
Project: Code from StackOverflow page How to read json file into java with simple JSON library
Code Author: https://stackoverflow.com/users/1212960/greg-kopff
Check this line
JSONArray cars = (JSONArray) JSONObject.get("cars");
change it with
JSONArray cars = (JSONArray) person.get("cars");
Issue was since you are calling the get method directly on the class.

Reading from a json file

I am trying to read from a json file and get only the phone numbers back i am using java and using the library org.json.simple and i am getting a error that says
"Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject
at Heatmap.main(Heatmap.java:21)"
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class Heatmap {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("c:\\clients.json"));
JSONObject jsonObject = (JSONObject) obj;
String phone = (String) jsonObject.get("Phone Number");
System.out.println(phone);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException ex) {
Logger.getLogger(Heatmap.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
According to the exception thrown, i think it could be that clients.json it's an array, so you should have something like this:
Object obj = parser.parse(new FileReader("c:\\clients.json"));
JSONArray jsonArray = (JSONArray) obj;
JSONObject client= (JSONObject)jsonObject.get("0");
String phone = (String) client.get("Phone Number");
System.out.println(phone);
Hope it helps !

Categories