JSON 错误:我不知道我拥有哪种类型的 json 文件。对象还是数组? "A JSONArray text must start with '[' at character 1"



这是我的JSON文件

{
"PartDetails": {
    "MyPricing": [{
        "BreakQuantity": 200,
        "UnitPrice": 0.3787,
        "TotalPrice": 75.74
    }, {
        "BreakQuantity": 600,
        "UnitPrice": 0.2932,
        "TotalPrice": 175.92
    }, {
        "BreakQuantity": 1000,
        "UnitPrice": 0.2525,
        "TotalPrice": 252.5
    }, {
        "BreakQuantity": 2600,
        "UnitPrice": 0.25,
        "TotalPrice": 650
    }]
}

这是我的java代码的一部分。我正在尝试退出我的定价。我对 JSON 很陌生。一些帮助会很好。我还不太了解语法。到目前为止,我一直在看一些视频,但无济于事。

JSONParser parser = new JSONParser();
    try {
        Object obj = parser.parse(new FileReader("C:/Users/Public/Documents/JSON/JSONFile.json"));
        // String jsonString="";
        JSONObject jsonObject = new JSONObject(obj.toString()).getJSONObject("PartDetails");
        System.out.println(jsonObject);
        JSONArray jsonArray = new JSONArray("MyPricing");
        for (int i = 0; i < jsonArray .length(); i++) {
            JSONObject _jObj = jsonArray.getJSONObject(i);
            JSONObject   _jObjTarget = _jObj.getJSONObject("target");
            String _indicator_name = _jObjTarget.getString("indicator_name");
            System.out.println("Indicator Name : " + _indicator_name);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
JSONArray jsonArray = new JSONArray("MyPricing"); -creates a new json array out of the string "MyPricing" (the string is not an array so this fails)

尝试:

 JSONArray jsonArray = jsonObject.getJSONArray("MyPricing"); - this takes the array that lies inside your object

最新更新