Home  >  Article  >  Java  >  Problems and solutions when using org json and fast json

Problems and solutions when using org json and fast json

零下一度
零下一度Original
2017-06-29 11:28:202736browse
1. Differences in values
When the obtained key does not exist:
org json will throw Exception
fast json will return null
Example:
com.alibaba.fastjson.JSONObject fastJson = new com.alibaba.fastjson.JSONObject( );
String name = fastJson.getString("name");
// fastJson normal output name:null
System.out.println("name:" + name);
org.json.JSONObject orgJson = new org.json.JSONObject();
//Throw exception: org.json.JSONException: JSONObject["name"] not found.
name = orgJson.getString("name");
System.out.println("name:" + name);
2. put org json in fast json
This operation is abnormal and empty json will be put
Example:
org.json.JSONObject orgJsonAddress = new org.json.JSONObject();
orgJsonAddress.put("country", " China");
orgJsonAddress.put("province", "Henan");
orgJsonAddress.put("city", "Zhengzhou");
com.alibaba.fastjson.JSONObject fastJson = new com.alibaba.fastjson.JSONObject();
fastJson.put("name", "Qingjiang Li");
fastJson.put("sex", 1);
fastJson.put("address", orgJsonAddress);
System.out.println(fastJson.toJSONString());
Exception output:
{
"address": {},
"sex": 1,
"name": "Qingjiang Li"
}
3. put fast json in org json
This operation is normal
Example:
com.alibaba.fastjson. JSONObject fastJsonAddress = new com.alibaba.fastjson.JSONObject();
fastJsonAddress.put("country", "China");
fastJsonAddress.put("province", "Henan" );
fastJsonAddress.put("city", "Zhengzhou");
org.json.JSONObject orgJson = new org.json.JSONObject();
orgJson.put("name", "Qingjiang Li");
orgJson.put("sex", 1);
orgJson.put("address", fastJsonAddress);
System.out.println(orgJson.toString());
Output is normal:
{
"address": {
"country": "China",
"province": "Henan",
"city": "Zhengzhou"
},
"sex": 1,
"name": "Qingjiang Li"
}
Conclusion:
In the project, try to use the same kind of JSON. If you have to use both, please be careful when using it and avoid Mistakes occur due to habits.

The above is the detailed content of Problems and solutions when using org json and fast json. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn