文章待补充,先写写以下知识点好了。

NULL值处理之 net.sf.json.JSONObject 和 com.alibaba.fastjson.JSONObject区别

JSON作为一个轻量级的文本数据交换格式常常用于web后台的数据封装和传输。JSON及其工具包给开发带来非常多的好处,提高了开发效率。然而,世间总是免不了存在一些坑,吾辈需笑看人生路,潜心研码。NULL值作为一个特殊情况,在处理的时候尤其需要小心处理。不幸的是,随着我们使用的工具类的作者的不同,对NULL的处理也有不同。此处,就扒一扒如题两家JSONObject工具类对NULL的处理。

问题来了,这两家对NULL是如何处理的,示例代码如下:

String resp = "{" +
" \"id\": \"123456fdae23\",\n" +
" \"userName\": \"dodoro\",\n" +
" \"cnName\": \"清风明月多多爱工作\",\n" +
" \"anull\": null,\n" +
" \"anothernull\": null,\n" +
"}"; JSONObject jsonObject = JSONObject.fromObject(resp);
if(jsonObject.getString("anull").equals("null")){
System.out.println("null became a string");
} com.alibaba.fastjson.JSONObject userInfo = com.alibaba.fastjson.JSONObject.parseObject(resp);
if(userInfo.getString("anull") == null){
System.out.println("alibaba NB, null is a null");
}
System.out.println(jsonObject);

运行的测试结果如下:

null became a string
alibaba NB, null is a null

结果很明显,net.sf.json.JSONObject将null转换成了一个字符串"null"com.alibaba.fastjson则是将null转换为了null,两者是有不同的。

首先,net.sf.json.JSONObject 提供了一个将其他类型的数据转换为转换为JSONObject的方法fromObject()

public static JSONObject fromObject(Object object) {
return fromObject(object, new JsonConfig());
}
public static JSONObject fromObject(Object object, JsonConfig jsonConfig) {
if(object != null && !JSONUtils.isNull(object)) {
if(object instanceof Enum) { //是否是枚举类型
throw new JSONException("\'object\' is an Enum. Use JSONArray instead");
} else if(!(object instanceof Annotation) && (object == null || !object.getClass().isAnnotation())) { //是否是注解类型
if(object instanceof JSONObject) { //是不是JSONObject
return _fromJSONObject((JSONObject)object, jsonConfig);
} else if(object instanceof DynaBean) {
return _fromDynaBean((DynaBean)object, jsonConfig);
} else if(object instanceof JSONTokener) {
return _fromJSONTokener((JSONTokener)object, jsonConfig);
} else if(object instanceof JSONString) { //是不是符合JSON格式的字符串
return _fromJSONString((JSONString)object, jsonConfig);
} else if(object instanceof Map) { //是不是Map
return _fromMap((Map)object, jsonConfig);
} else if(object instanceof String) { //是不是字符串
return _fromString((String)object, jsonConfig);
} else if(!JSONUtils.isNumber(object) && !JSONUtils.isBoolean(object) && !JSONUtils.isString(object)) {
if(JSONUtils.isArray(object)) { //是不是数组
throw new JSONException("\'object\' is an array. Use JSONArray instead");
} else {
return _fromBean(object, jsonConfig); //从对象转换为JSONObject,需要满足Bean的getter和setter
}
} else {
return new JSONObject();
}
} else {
throw new JSONException("\'object\' is an Annotation.");
}
} else {
return new JSONObject(true);
}
}

从其源代码可以看出net.sf.json功能强大,接口简洁,然而主要看的并不是这里,而是它的_fromJSONString((JSONString)object, jsonConfig); 方法。

private static JSONObject _fromString(String str, JsonConfig jsonConfig) {
if(str != null && !"null".equals(str)) {
return _fromJSONTokener(new JSONTokener(str), jsonConfig);
} else {
fireObjectStartEvent(jsonConfig);
fireObjectEndEvent(jsonConfig);
return new JSONObject(true);
}
} private static JSONObject _fromJSONTokener(JSONTokener tokener, JsonConfig jsonConfig) {
try {
if(tokener.matches("null.*")) {
fireObjectStartEvent(jsonConfig);
fireObjectEndEvent(jsonConfig);
return new JSONObject(true);
} else if(tokener.nextClean() != 123) {
throw tokener.syntaxError("A JSONObject text must begin with \'{\'");
} else {
fireObjectStartEvent(jsonConfig);
Collection exclusions = jsonConfig.getMergedExcludes();
PropertyFilter jsonPropertyFilter = jsonConfig.getJsonPropertyFilter();
JSONObject jsonObject = new JSONObject(); while(true) {
char jsone = tokener.nextClean();
switch(jsone) {
case '\u0000':
throw tokener.syntaxError("A JSONObject text must end with \'}\'");
case '}':
fireObjectEndEvent(jsonConfig);
return jsonObject;
default:
tokener.back();
String key = tokener.nextValue(jsonConfig).toString(); //此处取得一个token
jsone = tokener.nextClean();
if(jsone == 61) {
if(tokener.next() != 62) {
tokener.back();
}
} else if(jsone != 58) {
throw tokener.syntaxError("Expected a \':\' after a key");
} char peek = tokener.peek();
boolean quoted = peek == 34 || peek == 39;
Object v = tokener.nextValue(jsonConfig); //获取当前key的value
if(!quoted && JSONUtils.isFunctionHeader(v)) {
String params = JSONUtils.getFunctionParams((String)v); //转换为String袅
//省略.....
}

nextValue方法是JSONTokener类的方法,代码如下:

public Object nextValue(JsonConfig jsonConfig) {
char c = this.nextClean();
switch(c) {
case '\"':
case '\'':
return this.nextString(c);
case '[':
this.back();
return JSONArray.fromObject(this, jsonConfig);
case '{':
this.back();
return JSONObject.fromObject(this, jsonConfig);
default:
StringBuffer sb = new StringBuffer(); char b;
for(b = c; c >= 32 && ",:]}/\\\"[{;=#".indexOf(c) < 0; c = this.next()) {
sb.append(c);
} this.back();
String s = sb.toString().trim();
if(s.equals("")) {
throw this.syntaxError("Missing value.");
} else if(s.equalsIgnoreCase("true")) {
return Boolean.TRUE;
} else if(s.equalsIgnoreCase("false")) {
return Boolean.FALSE;
} else if(!s.equals("null") && (!jsonConfig.isJavascriptCompliant() || !s.equals("undefined"))) {
if((b < 48 || b > 57) && b != 46 && b != 45 && b != 43) {
if(!JSONUtils.isFunctionHeader(s) && !JSONUtils.isFunction(s)) {
switch(this.peek()) {
case ',':
case '[':
case ']':
case '{':
case '}':
throw new JSONException("Unquotted string \'" + s + "\'");
default:
return s;
}
} else {
return s;
}
} else {
if(b == 48) {
if(s.length() > 2 && (s.charAt(1) == 120 || s.charAt(1) == 88)) {
try {
return new Integer(Integer.parseInt(s.substring(2), 16));
} catch (Exception var13) {
;
}
} else {
try {
return new Integer(Integer.parseInt(s, 8));
} catch (Exception var12) {
;
}
}
} try {
return new Integer(s);
} catch (Exception var11) {
try {
return new Long(s);
} catch (Exception var10) {
try {
return new Double(s);
} catch (Exception var9) {
return s;
}
}
}
}
} else {
return JSONNull.getInstance(); //返回一个JSONNUll对象
}
}
} public final class JSONNull implements JSON { public String toString() {
return "null"; //返回一个“null”字符串
}
public String toString(int indentFactor) {
return this.toString();
}
}

至此可以看到net.sf.json将NULL转换为一个“null” 字符串处理。如果直接对存在null值得JSON对象使用getString进行操作,那么就容易出现使用getString("anull") == null的操作,而fastjson则是将null直接转换为一个null对象,所以可以直接使用getString("anull") == null进行比较。

万幸的是,如果我们通过JSON的方法将JSON对象转换为封装相同字段的JAVA对象,无论是哪种JSON工具包,最后都会把NULL转换为null

所以建议后台获取的JSON对象,如果想要使用,最好先转换为JAVABean来避免不同工具包之间的差异所带来的异常故障。

net.sf.json.JSONOBJECT.fromObject 与 com.alibaba.fastjson.JSONObject.parseObject的更多相关文章

  1. Json和Map互转,四个包(org.json/net.sf.json/com.google.gson/com.alibaba.fastjson)

    目前使用的(org.json/net.sf.json/com.google.gson/com.alibaba.fastjson)这四种json-map互转,其他的以后在补充.............. ...

  2. 42-字符串到json 的错误 com.alibaba.fastjson.JSONObject cannot be cast to java.lang.String

    json: {"updated_at":1551780617,"attr":{"uptime_h":3,"uptime_m&quo ...

  3. java后台接收json数据,报错com.alibaba.fastjson.JSONObject cannot be cast to xxx

    从前台接收json封装的list数据,在后台接收时一直报错,com.alibaba.fastjson.JSONObject cannot be cast to xxx, 使用这种方式接收可以接收 @R ...

  4. com.alibaba.fastjson.JSONObject之对象与JSON转换方法

    com.alibaba.fastjson.JSONObject时经常会用到它的转换方法,包括Java对象转成JSON串.JSON对象,JSON串转成java对象.JSON对象,JSON对象转换Java ...

  5. 探索RequestBody报com.alibaba.fastjson.JSONObject cannot be cast to xxx

    今天使用RequestBody接受前端传过来的参数,以前接受字符串数组非常成功,这次把形参改成了List<User>,原本以为顺利接受参数并映射成User的list结构,结果竟然在我取us ...

  6. No message body writer has been found for class com.alibaba.fastjson.JSONObject, ContentType: */*

    1:当使用 cxf 发布服务时,要求返回值类型为xml,或者json等 @Path("/searchProductByText") @GET @Produces({"ap ...

  7. com.alibaba.fastjson.JSONObject循环给同一对象赋值会出现"$ref":"$[0]"现象问题

    1.今天定义了一个JSONObject对象,引用的com.alibaba.fastjson.JSONObject,循环给这个对象赋值出现"$ref":"$[0]" ...

  8. com.alibaba.fastjson.JSONObject;的使用

    转: com.alibaba.fastjson.JSONObject;的使用 2018-11-04 23:51:23 mameng1998 阅读数 6404更多 分类专栏: java   1  POM ...

  9. Java-Class-I:com.alibaba.fastjson.JSONObject

    ylbtech-Java-Class-I:com.alibaba.fastjson.JSONObject 1.返回顶部 1.1.import com.alibaba.fastjson.JSON;imp ...

随机推荐

  1. 03 解析库之Beautifulsoup模块

    Beautifulsoup模块   一 介绍 Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库.它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式 ...

  2. Byte字节与位

    位(bit)字节(byte)一字节是8位所以2Byte是16位二进制

  3. webapp的优化总结

    1. 最先加载本地数据,下拉刷新再取最新数据. 2. 图片延后加载.一种方法先<div data-url="xx.png"></div>,先加载一个div, ...

  4. C变参数函数demo

    #include <stdio.h> #include <stdarg.h> int sum(int a,...) {     int temp = 0,sum=0,count ...

  5. ubuntu系统中安装RoboMongo

    1.下载RoboMongo RoboMongo官网下载链接.选择好相应版本. 2.解压文件 tar -xzf robomongo--linux-x86_64-.tar.gzcd robomongo-0 ...

  6. 使用JDBC连接MySql时出现:The server time zone value '�й���׼ʱ��' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration

    在连接字符串后面加上?serverTimezone=UTC 其中UTC是统一标准世界时间. 完整的连接字符串示例:jdbc:mysql://localhost:3306/test?serverTime ...

  7. head first 设计模式文摘

    1 欢迎来到设计模式世界:设计模式入门 2 让你的对象知悉现况:观察者模式 3 装饰对象:装饰者模式 4 工厂模式:烘烤OO的精华 5 单件模式:独一无二的对象 6 命令模式:封装调用 7 适配器模式 ...

  8. Django入门与实践-第24章:我的账户视图(完结)

    http://127.0.0.1:8000/settings/account/ #好的,那么,这部分将是我们最后的一个视图.之后,我们将专心来改进现有功能. #accounts/views.py fr ...

  9. 如何让编译器实现struts2的xml提示

    首先,选择pereference--->搜索xml 找到xml Catalog 点击右侧的add添加 下载好对应的dtd文档,然后在本地的WEB-INF下建立一个dtd文件夹,将dtd拷入. A ...

  10. Lucene.net 基本示例 《第一篇》

    Lucene.net是java平台搜索插件Lucene的移植版.它的主要用于开发搜索引擎,站内搜索等. 开篇之前,写个最简单的DEMO,让自己先体验下Lucene.net的魅力,顺便搭建环境. sta ...