關(guān)于JSON解析中獲取不存在的key問題
1 . fastjson
在fastjson中有些getXXX方法 , 如getString , getInteger , getIntValue等 , 當(dāng)調(diào)用getXXX方法時 , 如果傳入的key在json中不存在 , 那調(diào)用這些方法會報錯拋出異常嗎 ?
首先來看代碼demo
public static void main(String[] args) {
String str = "{\"name\":\"Bob\",\"age\":\"18123\"}";
JSONObject jsonObject = JSON.parseObject(str);
String[] keys = { "age" , "score"};
for(String key : keys){
System.out.println(jsonObject.getString(key));
System.out.println(jsonObject.getInteger(key));
System.out.println(jsonObject.getIntValue(key));
}
}運(yùn)行結(jié)果如下 :
18123
18123
18123
null
null
0
可看到 , 對不存在的key值(score)嘗試進(jìn)行g(shù)etXXX時 , 會返回當(dāng)前類型的默認(rèn)值(String返回null , Integer返回null , intValue返回0)
查看getString/getInteger源碼如下 :
public String getString(String key) {
Object value = get(key);
if (value == null) {
return null;
}
return value.toString();
}public Integer getInteger(String key) {
Object value = get(key);
return castToInt(value);
}getString就是調(diào)用get方法 , 然后判斷為null , 為null則返回null , 否則調(diào)用對象的toString()方法.getInteger就是相當(dāng)于調(diào)用get方法 , 然后調(diào)用castToInt方法將Ojbect對象轉(zhuǎn)換為Integer對象 , castToInt方法如下 :
public static Integer castToInt(Object value) {
if (value == null) {
return null;
}
if (value instanceof Integer) {
return (Integer) value;
}
if (value instanceof Number) {
return ((Number) value).intValue();
}
if (value instanceof String) {
String strVal = (String) value;
if (strVal.length() == 0 //
|| "null".equals(strVal) //
|| "NULL".equals(strVal)) {
return null;
}
if (strVal.indexOf(',') != 0) {
strVal = strVal.replaceAll(",", "");
}
return Integer.parseInt(strVal);
}
if (value instanceof Boolean) {
return ((Boolean) value).booleanValue() ? 1 : 0;
}
throw new JSONException("can not cast to int, value : " + value);
}首先看到第一個if中進(jìn)行了判斷 , 如果value值為null , 則直接返回null , 那getIntValue怎么判斷的呢 , getIntValue源碼如下 :
public int getIntValue(String key) {
Object value = get(key);
if (value == null) {
return 0;
}
return castToInt(value).intValue();
}原來在調(diào)用castToInt之前 ,就先做了一次null的判斷 , 為null直接返回了0 .
那調(diào)用get方法獲取一個不存在的key時 , 為什么會返回null而不是報錯呢 , 查看get源碼如下
public Object get(Object key) {
return map.get(key);
}map是JSONObject的一個成員變量
private final Map<String, Object> map;
原來 , JSONObject先將json字符串轉(zhuǎn)換為了一個map , 而map的get方法獲取不存在的key時 , 返回的就是null .
由此可以看到 , fastjson對不存在的key做了判斷 , 如果沒有則會返回類型的默認(rèn)值 .
2 . net.sf.json
public static void main(String[] args) {
String str = "{\"name\":\"Bob\",\"age\":\"18\"}";
JSONObject jsonObject = JSONObject.fromObject(str);
// System.out.println(jsonObject.get("gender"));//null
// System.out.println(jsonObject.getString("gender"));//JSONObject["gender"] not found
// System.out.println(jsonObject.getInt("age"));//18
System.out.println(jsonObject.getInt("score"));//JSONObject["score"] is not a number
}可以看到和fastjson的處理策略不同 , 它是對不存在的key拋出一個JSONException異常 , 查看源碼可以看到
public String getString(String key) {
this.verifyIsNull();
Object o = this.get(key);
if (o != null) {
return o.toString();
} else {
throw new JSONException("JSONObject[" + JSONUtils.quote(key) + "] not found.");
}
} public int getInt(String key) {
this.verifyIsNull();
Object o = this.get(key);
if (o != null) {
return o instanceof Number ? ((Number)o).intValue() : (int)this.getDouble(key);
} else {
throw new JSONException("JSONObject[" + JSONUtils.quote(key) + "] is not a number.");
}
}3 . org.json
和net.sf.json一樣 , org.json對不存在的key策略還是拋出異常 . 但org.json更加嚴(yán)格 , 在使用get("key")時就會直接拋出異常
public static void main(String[] args) throws Exception {
String str = "{\"name\":\"Bob\",\"age\":\"18\"}";
JSONObject jsonObject = new JSONObject(str);
System.out.println(jsonObject.get("gender"));//No value for gender
System.out.println(jsonObject.getString("gender"));//No value for gender
System.out.println(jsonObject.getInt("age"));//18
System.out.println(jsonObject.getInt("score"));//No value for score
}get方法源碼如下 :
public Object get(String name) throws JSONException {
Object result = nameValuePairs.get(name);
if (result == null) {
throw new JSONException("No value for " + name);
}
return result;
}getString源碼如下 , getInt與之類似 :
public int getInt(String name) throws JSONException {
Object object = get(name);
Integer result = JSON.toInteger(object);
if (result == null) {
throw JSON.typeMismatch(name, object, "int");
}
return result;
}以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
spring?boot使用攔截器修改請求URL域名?換?IP?訪問的方法
Spring Interceptor是一個非常類似于Servlet Filter 的概念 ,這篇文章主要介紹了spring?boot使用攔截器修改請求URL域名?換?IP?訪問的相關(guān)知識,需要的朋友可以參考下2022-09-09
解決redisTemplate向redis中插入String類型數(shù)據(jù)時出現(xiàn)亂碼問題
這篇文章主要介紹了解決redisTemplate向redis中插入String類型數(shù)據(jù)時出現(xiàn)亂碼問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-12-12
使用mybatis插件PageHelper實現(xiàn)分頁效果
這篇文章主要為大家詳細(xì)介紹了使用mybatis插件PageHelper實現(xiàn)分頁效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-01-01
Java Arrays.sort()如何實現(xiàn)對int類型數(shù)組倒序排序
這篇文章主要介紹了Java Arrays.sort()如何實現(xiàn)對int類型數(shù)組倒序排序問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-08-08

