如何在传递给另一个方法时处理不可用的JSON属性

vc9ivgsu  于 2023-06-25  发布在  其他
关注(0)|答案(1)|浏览(87)

Java初学者使用以下代码将嵌套对象的JSON数组解析为简化的JSON数组。如果JSON元素属性有一个正确的值或null,它工作正常,但如果属性不存在,它将抛出Null指针异常,请帮助我如何在数据解析方法内部处理这个问题。

import com.google.gson.*;

public class DataParser {

    public static JsonArray parseData(JsonArray data) throws JsonParseException {
    JsonArray dataArray = new JsonArray();
        for (JsonElement dataObj : data) {
            
            JsonObject obj = dataObj.getAsJsonObject();
            JsonObject finalDataObj = new JsonObject();            
            JsonObject fieldsObj = obj.getAsJsonObject("fields");
            finalDataObj.add("key", obj.get("key"));
            finalIssueObj.addProperty("cityName", getValue(fieldsObj.get("cityName")));
            finalIssueObj.addProperty("category", getValue(fieldsObj.get("category")));

            dataArray.add(finalDataObj);
        }

        return dataArray;
    }
    
     public static String getValue(JsonElement fieldValue){
         if(fieldValue.isJsonNull()) {
            return "";
        }
        else{
            return fieldValue.getAsString();
        }
    }

}
输入:

[{"key":"1232", "fields": {cityName":"Hyderabad","updated":"2023-05-31","category":"Dining"}},
{"key":"1233", "fields": {cityName":null,"updated":"2023-05-31","category":null}},
{"key":"1234", "fields": {cityName":"Delhi","updated":"2023-04-31"}}]

输出:

[{"key" : "1232", "cityName": "Hyderabad", "category" : "Dining"}, 
{"key" : "1233", "cityName": "", "category" : ""},
{"key" : "1234", "cityName": "Delhi", "category" : ""} ]
ie3xauqp

ie3xauqp1#

{"key":"1234", "fields": {cityName":"Delhi","updated":"2023-04-31"}

此记录没有category,因此在执行时

getValue(fieldsObj.get("category"))

fieldsObj.get("category")将返回null,并将null传递给方法getValue(JsonElement fieldValue),因此fieldValue将为null,fieldValue.isJsonNull()将抛出Null指针异常。null使用前需要判断

public static String getValue(JsonElement fieldValue){
     if(fieldValue==null || fieldValue.isJsonNull()) {
        return "";
    }
    else{
        return fieldValue.getAsString();
    }
}

相关问题