java 用Java读取json文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37816746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 02:50:31  来源:igfitidea点击:

Reading a json file in Java

javajsonparsing

提问by aze45sq6d

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". 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.

当我在另一个类中调用该方法时,该方法仅返回“0”,国家名称为“Neustadt”。基本上我想要的就是让这个函数返回某个城市的 ID。名称与 ID 一起存储在 Json 中。

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.

编辑:理想情况下,我希望能够解析位于项目内的 JSON 文件。我尝试使用 .getClass().getResource("/path/to/json"); 但这根本不起作用。

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

回答by OneCricketeer

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,您必须逐行读取文件并将每一行解析为JSONObject,您可以从中提取出所需的键值。