Java – 如何解析空的嵌套JSON数组

huangapple go评论74阅读模式
英文:

Java - How to Parse empty Nested Json Array

问题

JsonObject object = (JsonObject) new JsonParser().parse(jsonResponse);
JsonArray issuesArray = object.getAsJsonArray("issues");
for (int i = 0; i < issuesArray.size(); i++) {
    JsonObject currentissues = issuesArray.get(i).getAsJsonObject();
    String Issue_Id = currentissues.get("id").getAsString();
    String Issue_Key = currentissues.get("key").getAsString();
    String Issue_Type = currentissues.get("fields").getAsJsonObject().get("issuetype").getAsJsonObject().get("name").getAsString();
    JsonElement customfield = currentissues.get("fields").getAsJsonObject().get("customfield_29805");
    JsonArray completedCyclesArray = customfield.getAsJsonObject().getAsJsonArray("completedCycles");
    String Issue_FirstResponseStartTime = (completedCyclesArray.size() > 0) ? completedCyclesArray.get(0).getAsString() : "NULL";
}

请注意,我已经根据您提供的内容对代码进行了修改,以解决您遇到的问题。这段代码解析了您的JSON数据并提取了所需的字段,同时处理了您在customfield_29805中的情况。如果completedCycles数组不为空,则将其第一个值存储在Issue_FirstResponseStartTime变量中;如果为空,则将其设置为"NULL"。

英文:

I am trying to Parse below JSON data to String in Java using (GSON) Library, I am able to parse all JSON fields data except one of the JSON Array. I want to check if it's null/empty then in String variable store null value, if it's not then store the original value.

Input JSON Data:

{
    &quot;expand&quot;: &quot;schema,names&quot;,
    &quot;startAt&quot;: 0,
    &quot;maxResults&quot;: 50,
    &quot;total&quot;: 37875,
     &quot;issues&quot;: [
            {
                &quot;id&quot;: &quot;1190&quot;,
                &quot;key&quot;: &quot;GDS-81&quot;,
                &quot;fields&quot;: {
                    &quot;issuetype&quot;: {
                        &quot;id&quot;: &quot;2170&quot;,
                        &quot;name&quot;: &quot;Service Request with Approvals&quot;,
                        &quot;subtask&quot;: false
                    },
                    &quot;customfield_29805&quot;: {
                        &quot;id&quot;: &quot;26&quot;,
                        &quot;name&quot;: &quot;Issue - First Response&quot;,
                        &quot;completedCycles&quot;: []
                    }
    			}
    		}
    	]
     }

Code that I have done so far,

JsonObject object = (JsonObject) new JsonParser().parse(jsonResponse);				
JsonArray issuesArray = object.getAsJsonArray(&quot;issues&quot;);
for(int i=0; i&lt;issuesArray.size(); i++) {
    JsonObject currentissues = (JsonObject) issuesArray.get(i); 
    String Issue_Id = (String) currentissues.get(&quot;id&quot;).toString().replace(&quot;\&quot;&quot;, &quot;&quot;);
    String Issue_Key =  (String) currentissues.get(&quot;key&quot;).toString().replace(&quot;\&quot;&quot;, &quot;&quot;);	
    String Issue_Type = (String) currentissues.get(&quot;fields&quot;).getAsJsonObject().get(&quot;issuetype&quot;).getAsJsonObject().get(&quot;name&quot;).getAsString();
    JsonObject customfield = (JsonObject) currentissues.get(&quot;fields&quot;).getAsJsonObject().get(&quot;customfield_29805&quot;);
    JsonArray completedCyclesArray= customfield.getAsJsonArray(&quot;completedCycles&quot;);
    String Issue_FirstResponseStartTime = (completedCyclesArray.size() &gt; 0) ? completedCyclesArray.getAsString() : &quot;NULL&quot;;
}

However when I execute code I get below error on line :JsonObject customfield

java.lang.ClassCastException: com.google.gson.JsonNull cannot be cast to com.google.gson.JsonObject

Java – 如何解析空的嵌套JSON数组
1: https://i.stack.imgur.com/2wY0S.jpg

答案1

得分: 1

  1. 你不需要显式地将 JsonElement 转换为 JsonObject,而是使用 getAsJsonArray。一旦获得数组,就可以迭代其中的所有元素。

  2. 在检查 completedCyclesArray 的大小之前,你还需要处理 completedCyclesArray 的空值检查,否则会导致 NPE(空指针异常),我已经修复了这个问题。以下是修改后的可工作代码:

JsonParser parser = new JsonParser();
JsonArray array = parser.parse(jsonResponse).getAsJsonArray();
for (JsonElement e : array) {
    JsonObject currentissues = e.getAsJsonObject();
    String Issue_Id = currentissues.get("id").getAsString().replace("\"", "");
    String Issue_Key = currentissues.get("key").getAsString().replace("\"", "");
    String Issue_Type = currentissues.get("fields").getAsJsonObject().get("issuetype").getAsJsonObject().get("name").getAsString();
    JsonObject customfield = currentissues.get("fields").getAsJsonObject().get("customfield_29805").getAsJsonObject();
    JsonArray completedCyclesArray = customfield.getAsJsonArray("completedCycles");
    String Issue_FirstResponseStartTime = (completedCyclesArray != null && completedCyclesArray.size() > 0) ? completedCyclesArray.toString() : "NULL";
}
JsonObject object = new JsonParser().parse(jsonResponse).getAsJsonObject();
JsonArray issuesArray = object.getAsJsonArray("issues");
String expand = object.get("expand").getAsString();
String startAt = object.get("startAt").getAsString();
String maxResults = object.get("maxResults").getAsString();
String total = object.get("total").getAsString();
System.out.println(String.format("expand %s , startAt %s, maxResults %s, total %s", expand, startAt, maxResults, total));
issuesArray.forEach(currentissues -> {
    String Issue_Id = currentissues.get("id").getAsString().replace("\"", "");
    String Issue_Key = currentissues.get("key").getAsString().replace("\"", "");
    String Issue_Type = currentissues.get("fields").getAsJsonObject().get("issuetype").getAsJsonObject().get("name").getAsString();
    JsonObject customfield = currentissues.get("fields").getAsJsonObject().get("customfield_29805").getAsJsonObject();
    JsonArray completedCyclesArray = customfield.getAsJsonArray("completedCycles");
    String Issue_FirstResponseStartTime = (completedCyclesArray.size() > 0) ? completedCyclesArray.toString() : "NULL";
    System.out.println(String.format("Issue_Id %s , Issue_Key %s, Issue_Type %s, Issue_FirstResponseStartTime %s", Issue_Id, Issue_Key, Issue_Type, Issue_FirstResponseStartTime));
});

希望这些代码对你有所帮助。

英文:
  1. you dont need to explicitly , cast JsonElement to JsonObject instead use getAsJsonArray , Once you get your array, you can iterate through all the elements of it.

  2. You also need to handle null check for completedCyclesArray before checking its siz else it will give you the NPE , I have fixed that as well.
    Please find the modified working code as below

     JsonParser parser = new JsonParser();
     JsonArray array = parser.parse(jsonResponse).getAsJsonArray();
     for(JsonElement e : array) {
         JsonObject currentissues = (JsonObject) e;
         String Issue_Id = (String) currentissues.get(&quot;id&quot;).toString().replace(&quot;\&quot;&quot;, &quot;&quot;);
         String Issue_Key =  (String) currentissues.get(&quot;key&quot;).toString().replace(&quot;\&quot;&quot;, &quot;&quot;);
         String Issue_Type = (String) currentissues.get(&quot;fields&quot;).getAsJsonObject().get(&quot;issuetype&quot;).getAsJsonObject().get(&quot;name&quot;).getAsString();
         JsonObject customfield = (JsonObject) currentissues.get(&quot;fields&quot;).getAsJsonObject().get(&quot;customfield_29805&quot;);
         JsonArray completedCyclesArray= customfield.getAsJsonArray(&quot;completedCycles&quot;);
         String Issue_FirstResponseStartTime = (null != completedCyclesArray &amp;&amp; completedCyclesArray.size() &gt; 0) ? completedCyclesArray.getAsString() : &quot;NULL&quot;;
     }
    

    }

Please find my working solution for the updated json request(which not an array but nested json request)

JsonObject object = (JsonObject) new JsonParser().parse(jsonResponse);
JsonArray issuesArray = object.getAsJsonArray(&quot;issues&quot;);
String expand = object.get(&quot;expand&quot;).toString();
String startAt = object.get(&quot;startAt&quot;).toString();
String maxResults = object.get(&quot;maxResults&quot;).toString();
String total = object.get(&quot;total&quot;).toString();
System.out.println(String.format(&quot;expand %s , startAt %s, maxResults %s, total %s&quot;, expand, startAt, maxResults, total));
IntStream.range(0, issuesArray.size()).mapToObj(i -&gt; (JsonObject) issuesArray.get(i)).forEach(currentissues -&gt; {
    String Issue_Id = (String) currentissues.get(&quot;id&quot;).toString().replace(&quot;\&quot;&quot;, &quot;&quot;);
    String Issue_Key = (String) currentissues.get(&quot;key&quot;).toString().replace(&quot;\&quot;&quot;, &quot;&quot;);
    String Issue_Type = (String) currentissues.get(&quot;fields&quot;).getAsJsonObject().get(&quot;issuetype&quot;).getAsJsonObject().get(&quot;name&quot;).getAsString();
    JsonObject customfield = (JsonObject) currentissues.get(&quot;fields&quot;).getAsJsonObject().get(&quot;customfield_29805&quot;);
    JsonArray completedCyclesArray = customfield.getAsJsonArray(&quot;completedCycles&quot;);
    String Issue_FirstResponseStartTime = (completedCyclesArray.size() &gt; 0) ? completedCyclesArray.toString() : &quot;NULL&quot;;
    System.out.println(String.format(&quot;Issue_Id %s , Issue_Key %s, Issue_Type %s, Issue_FirstResponseStartTime %s&quot;, Issue_Id, Issue_Key, Issue_Type, Issue_FirstResponseStartTime));
});

and this is the output I got :

> expand "schema,names" , startAt 0, maxResults 50, total 37875 Issue_Id
> 1190 , Issue_Key GDS-81, Issue_Type Service Request with Approvals,
> Issue_FirstResponseStartTime NULL

Please see my complete working code here complete code

for both the secnarios

Empty completedCycles

{
    &quot;expand&quot;: &quot;schema,names&quot;,
    &quot;startAt&quot;: 0,
    &quot;maxResults&quot;: 50,
    &quot;total&quot;: 37875,
     &quot;issues&quot;: [
            {
                &quot;id&quot;: &quot;1190&quot;,
                &quot;key&quot;: &quot;GDS-81&quot;,
                &quot;fields&quot;: {
                    &quot;issuetype&quot;: {
                        &quot;id&quot;: &quot;2170&quot;,
                        &quot;name&quot;: &quot;Service Request with Approvals&quot;,
                        &quot;subtask&quot;: false
                    },
                    &quot;customfield_29805&quot;: {
                        &quot;id&quot;: &quot;26&quot;,
                        &quot;name&quot;: &quot;Issue - First Response&quot;,
                        &quot;completedCycles&quot;: []
                    }
    			}
    		}
    	]
     }

Non Empty completedCycles

{
&quot;expand&quot;: &quot;schema,names&quot;,
&quot;startAt&quot;: 0,
&quot;maxResults&quot;: 50,
&quot;total&quot;: 37875,
 &quot;issues&quot;: [
        {
            &quot;id&quot;: &quot;1190&quot;,
            &quot;key&quot;: &quot;GDS-81&quot;,
            &quot;fields&quot;: {
                &quot;issuetype&quot;: {
                    &quot;id&quot;: &quot;2170&quot;,
                    &quot;name&quot;: &quot;Service Request with Approvals&quot;,
                    &quot;subtask&quot;: false
                },
                &quot;customfield_29805&quot;: {
                    &quot;id&quot;: &quot;26&quot;,
                    &quot;name&quot;: &quot;Issue - First Response&quot;,
                      &quot;completedCycles&quot;: [{&quot;name&quot;:&quot;abc&quot;},{&quot;name&quot;: &quot;xyz&quot;}]
                }
            }
        }
    ]
 }

答案2

得分: 0

尝试在该语句的末尾添加 getAsJsonObject()。

英文:

Try adding getAsJsonObject() at the end of that statement.

huangapple
  • 本文由 发表于 2020年9月28日 01:57:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/64091610.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定