Gson.toJsonTree(intValue) throws Null pointer exception when trying to pass Integer parameter value

若如初见. 提交于 2020-06-29 04:15:19

问题


We are automating rest APIs using Rest Assured. During this process, trying to have a re-usable method created to pass different JSON nodes with different values.

Interger variable created:

Integer amt = 50;

Method created:

public void replaceValues_gson(String mainNode, String childNode, Integer amt) {        


        if(amt != null){
            jsonObjectNew.getAsJsonObject("mainNode").add("childNode", gson.toJsonTree(amt));
            } 
//here 'amt' throws an error as java.lang.NullPointerException; Also the amt it shows as 9 assigned to variable amt in the debugger where as it supposed to assign 50 value

    }

Calling above method as:

replaceValues_gson("bInfo", "bEx", amt );

Request JSON payload for the above is:

{
 "bInfo":{
  "bEx":9, 
  "oriDate":"2020-07-08"    

}
} 

Getting NullPointerException for 'amt' variable and Request JSON payload value is getting assigned rather assigning Integer amt value which is 50.

It works if directly trying like below:

jsonObjectNew.getAsJsonObject("bInfo").add("bEx", gson.toJsonTree(amt));

here amt variable value correctly goes as 50, but when trying to create re-usable method then throws an error.

Please guide.


回答1:


You can use the following method. But it does not support when the value that need to be updated is inside a json array.

public void replaceValues_gson(JsonObject jsonObjectNew, String[] keyArray, Object updatingValue) {

    Gson gson = new Gson();

    JsonObject jsonObject = jsonObjectNew;

    for (int i = 0; i < keyArray.length - 1; i++) {
        jsonObject = jsonObject.getAsJsonObject(keyArray[i]);
    }

    jsonObject.add(keyArray[keyArray.length - 1], gson.toJsonTree(updatingValue));

    System.out.println(jsonObjectNew.toString());

}

Here;

jsonObjectNew - the JsonObject converted from initial json request.

keyArray - String array of json node names from the root (in the exact order) including the key that need to be updated

updatingValue - value that will be updated

Eg:-

String[] keyArray = {"bInfo", "bEx"};
replaceValues_gson(jsonObjectNew, keyArray, 50);


来源:https://stackoverflow.com/questions/62250035/gson-tojsontreeintvalue-throws-null-pointer-exception-when-trying-to-pass-inte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!