java 在java中解析嵌套的json数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41016764/
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 05:37:24  来源:igfitidea点击:

Parsing nested json array in java

javaarraysjson

提问by vick_4444

I have json file in below format.

我有以下格式的json文件。

{
    "data":[ 
        {
          "prjId": 1,
          "name" : "Forj1",
          "issue": [
                    {
                      "id": 00001,
                      "status" : "Closed"
                    },
                    {
                      "id": 00002,
                      "status" : "Open"
                    }
                ]
          },  
          {
          "prjId": 2,
          "name" : "Forj2",
          "issue": [
                    {
                      "id": 00003,
                      "status" : "Closed"
                    },
                    {
                      "id": 00004,
                      "status" : "Open"
                    }
                ]
          }],
    "issueCounter": 7,
    "success": true
}

Here "data" is array of projects, and within project attribute there is array of "issue".

这里的“数据”是项目数组,在项目属性中有“问题”数组。

So far if I remove "issue" array, I am able to traverse the json to one level down in "data" attribute, If this json has "issue" array I get an error saying missing comma.

到目前为止,如果我删除“问题”数组,我可以将 json 遍历到“数据”属性中的下一级,如果此 json 有“问题”数组,我会收到一个错误,提示缺少逗号。

javax.json.stream.JsonParsingException: Invalid token=NUMBER at (line no=15, column no=14, offset=242) Expected tokens are: [COMMA]

Below is the code that I have right now. I have two problems with this, one is the error while reading if I place the "issue" attribute, and secondly a way to read the "issue" array and traverse all attributes within.

下面是我现在拥有的代码。我对此有两个问题,一个是如果我放置“问题”属性时读取的错误,其次是读取“问题”数组并遍历其中的所有属性的方法。

InputStream fis = new FileInputStream(pathToFile+"data3.json");
JsonReader jsonReader = Json.createReader(fis);

//the error is thrown on below line while reading the above json. 

JsonObject jsonObject = jsonReader.readObject();

jsonReader.close();
fis.close();

System.out.println(jsonObject.getInt("issueCounter"));

//reading arrays from json
JsonArray jsonArrayData = jsonObject.getJsonArray("data");
Project [] prj = new Project[jsonArrayData.size()];
int index = 0;
for(JsonValue value : jsonArrayData){

    JSONObject jsonObj = new JSONObject(value.toString());
    System.out.println(jsonObj.getString("name"));
    System.out.println(jsonObj.getInt("prjId"));

    //this is also the place where I am stuck, I know I need to construct an array out of it by obtaining issue attribute. Below is very very wrong.
    /*
    JsonArray jsonArrayIssue = jsonObj.getJsonArray("issue");
    for(JsonValue issue : jsonArrayIssue){

        JSONObject jsonIssueObj = new JSONObject(issue.toString());
        System.out.println(jsonIssueObj.getString("status"));
        System.out.println(jsonIssueObj.getInt("id"));
    }
    */
}

Any help or pointers is deeply appreciated. I can tweak the json if its required ultimately I need to maintain an array of issues.

任何帮助或指示深表感谢。如果需要,我可以调整 json 最终我需要维护一系列问题。

回答by isah

The problem as others said is the JSON. "id": 00001 <-- this is a number, numbers cannot start with a leading zero as per JSON stadard. If you control the JSON you should tweak it.

正如其他人所说,问题是 JSON。"id": 00001 <-- 这是一个数字,根据 JSON 标准,数字不能以前导零开头。如果您控制 JSON,则应该对其进行调整。

Alternatively ff you don't, you can use a less strict parser like org.json.simplehttps://mvnrepository.com/artifact/com.googlecode.json-simple/json-simpleThe code will be the same as yours, just adjusted to org.json.simple

或者,如果您不这样做,您可以使用不太严格的解析器,例如org.json.simplehttps://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple代码将与您的相同,只是调整为org.json.simple

try {   ...
        JSONObject rootJSON = (JSONObject) new JSONParser().parse(jsonString);
        JSONArray dataList = (JSONArray) rootJSON.get("data");
        for(Object projectObj: dataList.toArray()){
            JSONObject project = (JSONObject)projectObj;
            JSONArray issueList = (JSONArray) project.get("issue");
            for(Object issueObj: issueList.toArray()){
                JSONObject issue = (JSONObject) issueObj;
                //do something with the issue
            }
        }
    } catch (ParseException e) {
        //do smth
        e.printStackTrace();
    }

回答by Javasamurai

Your json data is invalid.You can check here. http://jsonlint.com
...issue": [{ "id": 00001,
"status": ----------------------^
Your id must be string number,string,boolean.Send 1,2,3,.... as return values and check if it works.

您的 json 数据无效。您可以在这里查看。 http://jsonlint.com您的 id 必须是字符串 number,string,boolean.Send 1,2,3,.... 作为返回值并检查它是否有效。
...issue": [{ "id": 00001,
"status": ----------------------^

回答by David

Your code looks okay the problem is the JSON formatting. Specifically the following lines:

您的代码看起来没问题,问题在于 JSON 格式。具体如下几行:

"id": 00001, "id": 00002, "id": 00003, "id": 00004,

“id”:00001,“id”:00002,“id”:00003,“id”:00004,

Basically if you want it in that format you will need to set them as strings by wrapping the values in quotations i.e. "id": "00001" or you can use a valid number i.e. "id": 1

基本上,如果您希望采用这种格式,则需要通过将值括在引号中来将它们设置为字符串,即“id”:“00001”,或者您可以使用有效数字,即“id”:1