0

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:

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

Code that I have done so far,

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

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

[![UpdatedCode StackTrace][1]][1] [1]: https://i.sstatic.net/2wY0S.jpg

1

2 Answers 2

1
  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("id").toString().replace("\"", "");
         String Issue_Key =  (String) currentissues.get("key").toString().replace("\"", "");
         String Issue_Type = (String) currentissues.get("fields").getAsJsonObject().get("issuetype").getAsJsonObject().get("name").getAsString();
         JsonObject customfield = (JsonObject) currentissues.get("fields").getAsJsonObject().get("customfield_29805");
         JsonArray completedCyclesArray= customfield.getAsJsonArray("completedCycles");
         String Issue_FirstResponseStartTime = (null != completedCyclesArray && completedCyclesArray.size() > 0) ? completedCyclesArray.getAsString() : "NULL";
     }
    

    }

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("issues");
String expand = object.get("expand").toString();
String startAt = object.get("startAt").toString();
String maxResults = object.get("maxResults").toString();
String total = object.get("total").toString();
System.out.println(String.format("expand %s , startAt %s, maxResults %s, total %s", expand, startAt, maxResults, total));
IntStream.range(0, issuesArray.size()).mapToObj(i -> (JsonObject) issuesArray.get(i)).forEach(currentissues -> {
    String Issue_Id = (String) currentissues.get("id").toString().replace("\"", "");
    String Issue_Key = (String) currentissues.get("key").toString().replace("\"", "");
    String Issue_Type = (String) currentissues.get("fields").getAsJsonObject().get("issuetype").getAsJsonObject().get("name").getAsString();
    JsonObject customfield = (JsonObject) currentissues.get("fields").getAsJsonObject().get("customfield_29805");
    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));
});

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

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

Non Empty completedCycles

{
"expand": "schema,names",
"startAt": 0,
"maxResults": 50,
"total": 37875,
 "issues": [
        {
            "id": "1190",
            "key": "GDS-81",
            "fields": {
                "issuetype": {
                    "id": "2170",
                    "name": "Service Request with Approvals",
                    "subtask": false
                },
                "customfield_29805": {
                    "id": "26",
                    "name": "Issue - First Response",
                      "completedCycles": [{"name":"abc"},{"name": "xyz"}]
                }
            }
        }
    ]
 }
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks, but JSON response which I get is not just a block of JSONArray it also has some parameters at the beginning (startAt, maxResults, etc) which I have updated in my post and hence code is failing with error java.lang.IllegalStateException: This is not a JSON Array.
Its still failing on statement IntStream.range(0, issuesArray.size()).mapToObj(i -> (JsonObject) issuesArray.get(i)).forEach(currentissues -> { For Detail Stack trace check i.sstatic.net/2wY0S.jpg
fixed , instead of using completedCyclesArray.getAsString() we should use completedCyclesArray.toString() , Please retest
I updated code, but still failing with same error: java.lang.ClassCastException: com.google.gson.JsonNull cannot be cast to com.google.gson.JsonObject and same stack trace. :(
can you send me the requested json? also complete code , since it is perfectly working on my machine
|
0

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

1 Comment

I added getAsJsonObject() at the end of that statment ( JsonObject customfield) , but it failed with error java.lang.IllegalStateException: Not a JSON Object: null

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.