[英]Reading a json file in Java
So I am having troubles with reading a Json file in Java. 所以我在阅读Java中的Json文件时遇到了麻烦。
It is a Json file with content in this format: 它是一个Json文件,其内容采用以下格式:
{
"_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". 当我在另一个类中调用该方法时,该方法只返回一个“0”,国家名称为“Neustadt”。 Basically all I want is for this function to return the ID for a certain city.
基本上我想要的是这个函数返回某个城市的ID。 The names are stored in the Json, together with the ID.
名称与ID一起存储在Json中。
Edit: Ideally I want to be able to parse the JSON file, which is located inside the project. 编辑:理想情况下,我希望能够解析位于项目内的JSON文件。 I tried using .getClass().getResource("/path/to/json");
我尝试使用.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. 因此,您不能将整个文件抛出到
JSONParser
,您必须JSONParser
读取该文件并将每行解析为JSONObject
,您可以从中提取所需的键值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.