【问题标题】:Gson.toJsonTree(intValue) throws Null pointer exception when trying to pass Integer parameter valueGson.toJsonTree(intValue) 尝试传递 Integer 参数值时抛出 Null 指针异常
【发布时间】:2020-06-07 18:42:56
【问题描述】:

我们正在使用 Rest Assured 自动化休息 API。在此过程中,尝试创建一个可重用的方法来传递具有不同值的不同 JSON 节点。

已创建整数变量:

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 有效负载是:

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

}
} 

正在为“amt”变量和请求 JSON 有效负载值分配 NullPointerException,而不是分配整数 amt 值,即 50。

如果像下面这样直接尝试就可以了:

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

这里的 amt 变量值正确地为 50,但是当尝试创建可重用的方法时会抛出错误。

请指导。

【问题讨论】:

    标签: gson rest-assured


    【解决方案1】:

    您可以使用以下方法。但不支持需要更新的值在json数组内时。

    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。

    keyArray - 来自根的 json 节点名称字符串数组(按确切顺序),包括需要更新的键

    updatingValue - 将被更新的值

    例如:-

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

    【讨论】:

    • 感谢您的宝贵指导,因为我们有 100 多个 API 正在尝试使用可重用的方法。
    猜你喜欢
    • 2021-05-02
    • 1970-01-01
    • 2015-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 2015-12-28
    相关资源
    最近更新 更多