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" : ""} ]
1条答案
按热度按时间ie3xauqp1#
此记录没有
category
,因此在执行时fieldsObj.get("category")
将返回null
,并将null
传递给方法getValue(JsonElement fieldValue)
,因此fieldValue
将为null,fieldValue.isJsonNull()
将抛出Null指针异常。null
使用前需要判断