有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

从JSON文件Java获取字符串

我想使用“JSON SIMPLE”API读取JSON文件

JSONParser parser = new JSONParser();
JSONArray a = null;
try {
    a = (JSONArray) parser.parse(new FileReader("C:\\data\\data.json"));
} catch (IOException | ParseException e1) {
    e1.printStackTrace();
}

for (Object o : a) {
    JSONObject jsonObject =  (JSONObject) o;

    String name = (String) jsonObject.get("Test");
    System.out.println(name);
}

我的JSON文件:

{
    "Test" : {
        "Tenorhorn" : "2",
        "Tuba" : "2",
        "Posaune" : "3",
        "Schreibweise" : "B",
        "SonstigeInst" : "",
        "Author" : "tesaf",
        "Wertung" : "1",
        "Trompete" : "2",
        "Partitur" : "Partitur",
        "Path" : ""
    }
}

但我有以下例外:

"Unexpected token LEFT BRACE({) at position 237."

At position 237 is: `               } catch (IOException | ParseException e1) {

`


共 (2) 个答案

  1. # 1 楼答案

    "Unexpected token LEFT BRACE({) at position 237."
    At position 237 is: `               } catch (IOException | ParseException e1) {
    

    听起来像

    } catch (IOException | ParseException e1) {
    

    在Json文件中是意外的

  2. # 2 楼答案

    首先,您提供的JSON是一个JSONObject而不是数组。要解析它,以下代码块将起作用

    JSONParser  parser = new JSONParser();
        JSONObject a = null;
        try {
            FileReader fileReader = new FileReader("C:\\data\\data.json");
            a = (JSONObject) parser.parse(fileReader);
        } catch (Exception e1) {
            e1.printStackTrace();
        }        
         System.out.println(a.get("Test"));
    

    输出将是:{“Tenorhorn”:“2”,“Tuba”:“2”,“Posune”:“3”,“Schreibweise”:“B”,“SonstigeInst”:“Author”:“tesaf”,“Trompete”:“2”,“Wertung”:“1”,“Partitur”:“Partitur”,“Path”:“}

    为了回答关于数组的问题,可以使用Json数组而不是单个Json对象

    例如:

    [{
    "Tenorhorn": "2",
    "Tuba": "2",
    "Posaune": "3",
    "Schreibweise": "B",
    "SonstigeInst": "",
    "Author": "tesaf",
    "Wertung": "1",
    "Trompete": "2",
    "Partitur": "Partitur",
    "Path": ""
    

    }]

    您的代码将是

    JSONArray a = null;
        try {
            FileReader fileReader = new FileReader("C:\\data\\data.json");
            a = (JSONArray) parser.parse(fileReader);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    
        for (Object o : a) {
            JSONObject jsonObject =  (JSONObject) o;
    
            System.out.println(jsonObject);
        }
    

    还有一件事需要记住的是IOException | ParseException e1-如果使用低于1.7的JDK,则不允许使用多捕获参数