aze45sq6d aze45sq6d - 7 months ago 183
JSON Question

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:


This is the code I am using:

* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
package controllers;

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;

* @author Jean
@Named(value = "cityID")
public class getCityIDs implements Serializable{

private static final String filePath = "C:\\Users\\User\\Documents\\NetBeansProjects\\PhpProject1\\Reis\\RBureau222\\web\\json\\city.list.json";

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");

long id = (long) jsonObject.get("_id");
return id;
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);


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(

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.

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.


Your data is line-delimited


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.