尝试传递Integer参数值时,Gson.toJsonTree(intValue)引发Null指针异常 [英] Gson.toJsonTree(intValue) throws Null pointer exception when trying to pass Integer parameter value
问题描述
我们正在使用Rest Assured自动化Rest API.在此过程中,尝试创建可重用的方法以传递具有不同值的不同JSON节点.
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变量:
Interger variable created:
Integer amt = 50;
创建的方法:
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
}
调用上述方法为:
replaceValues_gson("bInfo", "bEx", amt );
以上请求的JSON有效负载为:
Request JSON payload for the above is:
{
"bInfo":{
"bEx":9,
"oriDate":"2020-07-08"
}
}
获取"amt"变量的NullPointerException和请求JSON有效负载值,而分配的是整数amt值50.
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));
这里的amt变量值正确为50,但是在尝试创建可重用方法时会引发错误.
here amt variable value correctly goes as 50, but when trying to create re-usable method then throws an error.
请指导.
推荐答案
您可以使用以下方法.但是,当需要更新的值位于json数组中时,它不支持.
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());
}
在这里;
jsonObjectNew
-从初始json请求转换的JsonObject.
jsonObjectNew
- the JsonObject converted from initial json request.
keyArray
-根节点的json节点名称的字符串数组(按确切顺序),包括需要更新的密钥
keyArray
- String array of json node names from the root (in the exact order) including the key that need to be updated
updatingValue
-将被更新的值
例如:-
String[] keyArray = {"bInfo", "bEx"};
replaceValues_gson(jsonObjectNew, keyArray, 50);
这篇关于尝试传递Integer参数值时,Gson.toJsonTree(intValue)引发Null指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!