我需要解析存储在单个文件中的 json 列表!
到目前为止我所做的是, test.json 文件包含:
{"location":"lille","lat":28.4,"long":51.7,"country":"FR"}
有了这个文件,我有下面的代码
public class JsonReader {
public static void main(String[] args) throws ParseException {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("c:\\test.json"));
JSONObject locationjson= (JSONObject) obj;
String location= (String) locationjson.get("location");
System.out.printf("%s",location);
long lat = (Long) locationjson.get("lat");
System.out.printf("\t%d",lat);
//similarly for other objects
这是一个工作代码,我只能打印文件 test.json 中的一个 json
现在,如果我必须在文件 test1.json 中打印 json 列表,如下所示:每一行都是一个有效的 json,并且单个文件中有 json 列表。我需要的是解析每个 json 并在每一行中打印它。使用 bean 类可以吗?
{"Atlas":{"location":"lille","lat":28.4,"long":51.7,"country":"FR"}}
{"Atlas":{"location":"luxum","lat":24.1,"long":54.7,"country":"LU"}}
{"Atlas":{"location":"ghent","lat":28.1,"long":50.1,"country":"BE"}}
{"Atlas":{"location":"alborg","lat":23.4,"long":53.7,"country":"DN"}}
感谢您的帮助!
最佳答案
JSON 应该有一个根节点。
如果没有,您可以从文件中逐行读取,并将每一行传递到包装在 StringReader
中的 JSONParser
(因为JSONParser.parse()
方法采用 Reader
)。
例如
BufferedReader in
= new BufferedReader(new FileReader("test.json"));
while(!done) {
String s = in.readLine();
if (s == null) {
done = true;
}
else {
StringReader sr = new StringReader(s);
// etc...
}
}
编辑:我假设您正在使用 JSONParser 。如果您使用不同的解析器(哪一个?),那么它可能采用String
参数。
关于java - 解析json列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11754806/