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.
Related
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) {
}
});
}
}
}
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();
}
}
}
When jsonobject is converted to String or long it returns null. Why?
My JSON file:
{
"memberships": [
{
"project": {
"id": 30483134480107,
"name": "Asana Integrations"
},
"section": null
}
]
}
And my code:
package jsontest;
import java.beans.Statement;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.Scanner;
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 MoreComplexJson {
private static final String filePath = "C:\\jsonTestFile.json";
public static void main(String[] args) {
try {
FileReader reader = new FileReader(filePath);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
JSONArray memberships = (JSONArray) jsonObject.get("memberships");
for (int z = 0; z < memberships.size(); z++) {
Iterator m = memberships.iterator();
// take each value from the json array separately
while (m.hasNext()) {
JSONObject innerObj = (JSONObject) m.next();
Long id = (Long) innerObj.get("id");
String name = (String) innerObj.get("name");
System.out.println("id " + id + " with name " + name);
}
}
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
System.out.println(ex + "");
}
catch (IOException ex) {
ex.printStackTrace();
ex.printStackTrace();
System.out.println(ex + "");
}
catch (ParseException ex) {
ex.printStackTrace();
ex.printStackTrace();
System.out.println(ex + "");
}
catch (NullPointerException ex) {
ex.printStackTrace();
ex.printStackTrace();
System.out.println(ex + "");
}
}
}
The output:
id null with name null
id and name belongs to the project JSONObject so get those two values using the project JSONObject
Try this for loop
for (int z = 0; z < memberships.size(); z++) {
JSONObject m = (JSONObject) memberships.get(z);
JSONObject innerObj = (JSONObject) m.get("project");
// If you want section
String section = (String) m.get("section");
System.out.println("section " + section);
Long id = (Long) innerObj.get("id");
String name = (String) innerObj.get("name");
System.out.println("id " + id + " with name " + name);
}
The problem is that when you are trying to get id and name you're not taking it from project but from object that contains project. There should be:
JSONObject innerObj = (JsonObject) ((JSONObject) m.next()).get("project)";
This kind of code can get pretty ugly pretty fast. Instead you could use a higher order parser, such as Jackson. Then your code can be much cleaner and you don't have to worry about digging into the conversion of each piece of JSON.
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 !
I have a java code:
URL oracle = new URL("https://x.x.x.x.x.x.-001");
System.out.println(oracle.openStream());
BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
Which is opening the connection and printing the contents of it. The contents are indeed Json. The output is something like:
{
"merchantId": "guest",
"txnId": "guest-1349269250-001",
}
I wish to parse this in json simple jar. I changed the code loop like this:
JSONObject obj = new JSONObject();
while ((inputLine = in.readLine()) != null)
obj.put("Result",inputLine);
But that doesn't seem to be working. The output I'm getting is:
{"Result":"}"}
You should use the JSONParser#Parse() method or the JSONValue#parse() method :
URL oracle = new URL("https://x.x.x.x.x.x.-001");
System.out.println(oracle.openStream());
Reader in = new InputStreamReader(oracle.openStream());
Object json = JSONValue.parse(in);
Are you sure you're following the documentation on how to parse a JSON string?
By the looks of it you have to obtain the entire string and call a JSONParse#parse() on it, but your code is filling up a HashMap (JSONObject's parent class) with each of the lines of the JSON. In fact it stores just the last line because you're calling put() with the same "Result" key on every iteration.
You should read whole contents to String variable first and parse it to json. Be careful of ""(double quote). Java uses \" for double quote. Like.
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JsonSimpleExample3 {
public static void main(String args[]) {
JSONParser parser = new JSONParser();
//String str = "{\"merchantId\": \"guest\",\"txnId\": \"guest-1349269250-001\",}";
//intilize an InputStream
InputStream is = new ByteArrayInputStream("file content".getBytes());
//read it with BufferedReader and create string
BufferedReader br = new BufferedReader(new InputStreamReader(is));// Instead of is, you should use oracle.openStream()
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e1) {
e1.printStackTrace();
}
// parse string
try {
JSONObject jsonObject = (JSONObject) parser.parse(sb.toString());
String merchantId = (String) jsonObject.get("merchantId");
System.out.println(merchantId);
String txnId = (String) jsonObject.get("txnId");
System.out.println(txnId);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
try this link its really helpful if you are going to be logging in or staff like that
Java Json simple
import java.io.IOException;
import java.net.URL;
import org.apache.commons.io.IOUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.ParseException;
public class ParseJson1 {
public static void main(String[] args) {
String url = "http://freemusicarchive.org/api/get/genres.json?api_key=60BLHNQCAOUFPIBZ&limit=2";
/*
* {"title":"Free Music Archive - Genres","message":"","errors":[],"total" : "161","total_pages":81,"page":1,"limit":"2",
* "dataset":
* [{"genre_id": "1","genre_parent_id":"38","genre_title":"Avant-Garde" ,"genre_handle": "Avant-Garde","genre_color":"#006666"},
* {"genre_id":"2","genre_parent_id" :null,"genre_title":"International","genre_handle":"International","genre_color":"#CC3300"}]}
*/
try {
String genreJson = IOUtils.toString(new URL(url));
JSONObject genreJsonObject = (JSONObject) JSONValue.parseWithException(genreJson);
// get the title
System.out.println(genreJsonObject.get("title"));
// get the data
JSONArray genreArray = (JSONArray) genreJsonObject.get("dataset");
// get the first genre
JSONObject firstGenre = (JSONObject) genreArray.get(0);
System.out.println(firstGenre.get("genre_title"));
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}
}