用Java读取json文件 [英] Reading a json file in Java

查看:122
本文介绍了用Java读取json文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在用 Java 读取 Json 文件时遇到了麻烦.

So I am having troubles with reading a Json file in Java.

这是一个 Json 文件,内容格式如下:

It is a Json file with content in this format:

{
  "_id": 2864071,
  "name": "Neustadt",
  "country": "DE",
  "coord": {
    "lon": 12.56667,
    "lat": 52.400002
  }
}

这是我使用的代码:

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

存在:

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.

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

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.

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

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.

已修复

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

推荐答案

您的数据以行分隔

{"_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}}

因此,您不能将整个文件扔到 JSONParser 中,您必须逐行读取文件并将每一行解析为 JSONObject,从中您可以提取出所需的键值.

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.

这篇关于用Java读取json文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆