转:

net.sf.json.JSONObject处理 "null" 字符串的一些坑

2018年05月02日 16:41:25 大白能 阅读数:7026
 
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_28988969/article/details/80168447

添加依赖

<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

示例代码

package com.ahut;

import net.sf.json.JSONObject;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest; import java.util.Map; @SpringBootTest
public class ConfigClientApplicationTests { @Test
public void contextLoads() { JSONObject jsonObject = new JSONObject();
jsonObject.put("key", "null");
jsonObject.put("key2", "notNull"); Map itemsMap = (Map) jsonObject; System.out.println(jsonObject.get("key").getClass());//class net.sf.json.JSONNull
System.out.println(jsonObject.get("key2").getClass());//class java.lang.String System.out.println(itemsMap.get("key").equals("null"));//true
System.out.println("null".equals(itemsMap.get("key")));//false System.out.println(itemsMap.get("key2").equals("notNull"));//true
System.out.println("notNull".equals(itemsMap.get("key2")));//true
} }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

运行结果:

class net.sf.json.JSONNull
class java.lang.String
true
false
true
true
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

代码分析

net.sf.json.JSONObject本身就实现了Map接口:

public final class JSONObject extends AbstractJSON
implements JSON, Map, Comparable {
...
}
  • 1
  • 2
  • 3
  • 4

其内部维护了一个Map属性,实际就是一个HashMap:

// 成员变量
private Map properties; // 构造方法
public JSONObject() {
this.properties = new ListOrderedMap();
} public ListOrderedMap() {
this(new HashMap());
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

注意:

  • 非”null”字符串放到JSONObject类中时,取出来使用时是java.lang.String类型
  • “null”字符串放到JSONObject类中时,取出来的使用会转换成net.sf.json.JSONNull类型:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
// package net.sf.json; import java.io.IOException;
import java.io.Writer; public final class JSONNull implements JSON {
private static JSONNull instance = new JSONNull(); public static JSONNull getInstance() {
return instance;
} private JSONNull() {
} public boolean equals(Object object) {
return object == null || object == this || object == instance || object instanceof JSONObject && ((JSONObject)object).isNullObject() || "null".equals(object);
} public int hashCode() {
return 37 + "null".hashCode();
} public boolean isArray() {
return false;
} public boolean isEmpty() {
throw new JSONException("Object is null");
} public int size() {
throw new JSONException("Object is null");
} public String toString() {
return "null";
} public String toString(int indentFactor) {
return this.toString();
} public String toString(int indentFactor, int indent) {
StringBuffer sb = new StringBuffer(); for(int i = 0; i < indent; ++i) {
sb.append(' ');
} sb.append(this.toString());
return sb.toString();
} public Writer write(Writer writer) {
try {
writer.write(this.toString());
return writer;
} catch (IOException var3) {
throw new JSONException(var3);
}
}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69

这就是为什么:

System.out.println(jsonObject.get("key").getClass());//class net.sf.json.JSONNull

System.out.println(jsonObject.get("key2").getClass());//class java.lang.String
  • 1
  • 2
  • 3

itemsMap.get(“key”).equals(“null”)

分析:

JSONObject jsonObject = new JSONObject();

jsonObject.put("key", "null");

Map itemsMap = (Map) jsonObject;

System.out.println(itemsMap.get("key").equals("null"));
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

键为 “key” 的值对应 “null” 字符串
所以itemsMap.get(“key”)获取到的类型是JSONNull
所以itemsMap.get(“key”).equals(“null”)中的equals调用的是JSONNull中的equals方法

public boolean equals(Object object) {
return object == null || object == this || object == instance || object instanceof JSONObject && ((JSONObject)object).isNullObject() || "null".equals(object);
}
  • 1
  • 2
  • 3

所以:

System.out.println(itemsMap.get("key").equals("null"));//true
  • 1

“null”.equals(itemsMap.get(“key”))

分析:

JSONObject jsonObject = new JSONObject();

jsonObject.put("key", "null");

Map itemsMap = (Map) jsonObject;

System.out.println("null".equals(itemsMap.get("key")));
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

此时”null”.equals(itemsMap.get(“key”))调用的equals是String类的equals方法:


/**
* String复写的equals方法
*/
public boolean equals(Object anObject) { // 比较地址是否相同,两个应用指向同一个对象(同一个地址)
if (this == anObject) {
return true;
} // 判断是否是String类
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
} // 返回结果
return false;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

执行分析:

  • itemsMap.get(“key”)获取到的是net.sf.json.JSONNull类型
  • net.sf.json.JSONNull和”null”不是同一个对象,继续向下执行
  • net.sf.json.JSONNull不是String类型,继续向下执行
  • return false

所以:

System.out.println("null".equals(itemsMap.get("key")));//false

net.sf.json.JSONObject处理 "null" 字符串的一些坑的更多相关文章

  1. net.sf.json.JSONOBJECT.fromObject 与 com.alibaba.fastjson.JSONObject.parseObject

    文章待补充,先写写以下知识点好了. NULL值处理之 net.sf.json.JSONObject 和 com.alibaba.fastjson.JSONObject区别 JSON作为一个轻量级的文本 ...

  2. net.sf.json JSONObject与JSONArray使用实例

    实例自己想的一个实例应用场景:一个人可以有多个角色,例如:在家中是儿子,在学校是学生,在公司是程序员,一个人还可以办好多业务 * 每个业务好多个人都可以办,则标记(mark)就是记录这唯一标识的(如i ...

  3. 使用JSONObject遇到的问题,java.lang.NoClassDefFoundError: net/sf/json/JSONObject

    先是报 java.lang.NoClassDefFoundError: net/sf/json/JSONObject 这个错误, 打开项目属性找到java build path中的libaries,找 ...

  4. net.sf.json.JSONObject 和org.json.JSONObject 的差别

    http://my.oschina.net/wangwu91/blog/340721 net.sf.json.JSONObject 和org.json.JSONObject  的差别. 一.创建jso ...

  5. net.sf.json.JSONObject 和org.json.JSONObject

    参考 net.sf.json.JSONObject 和org.json.JSONObject 的差别

  6. net.sf.json JSONObject与JSONArray总结

    JSONObject:json对象,就是一个键对应一个值,使用的是大括号{ },如:{key:value} JSONArray:json数组,使用中括号[ ],只不过数组里面的项也是json键值对格式 ...

  7. net.sf.json.JSONObject maven下载到了但是java后台一直用不了问题

    需求,实体转JSON,然后用到JSONObject转JSON,但是我向下面这样引入,后台就是用不了,还是报红, <dependency> <groupId>net.sf.jso ...

  8. 记一次未解决的异常:java.lang.NoClassDefFoundError: net/sf/json/JSONObject

    原因:Jetty会导致这个问题,Tomcat可以正常启动   一.异常产生现象 使用json-lib转换实体类/字符串,跑单元测试没问题,但是启动jetty后调用JSONArray.fromObjec ...

  9. Jetty+json-lib库抛异常的问题解决过程(java.lang.NoClassDefFoundError: net/sf/json/JSONObject)

      一.之前抛异常是将json库改成了fastjson解决的,参见: http://www.cnblogs.com/gossip/p/5369670.html     异常信息:     二.解决步骤 ...

随机推荐

  1. Linux CentOS 7 防火墙与端口设置操作

    CentOS升级到7之后用firewall代替了iptables来设置Linux端口, 下面是具体的设置方法: []:选填 <>:必填 [<zone>]:作用域(block.d ...

  2. Kaggle_泰坦尼克乘客存活预测

    转载 逻辑回归应用之Kaggle泰坦尼克之灾 此转载只为保存!!! ————————————————版权声明:本文为CSDN博主「寒小阳」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附 ...

  3. 广告域名审核之后跳转技术:点击域名A页面iframe框架下的链接,域名A跳转到域名B

    广告域名审核之后跳转技术:点击域名A页面iframe框架下的链接,域名A跳转到域名B注:域名B为afish.cnblogs.com 域名A页面代码:<!DOCTYPE html PUBLIC & ...

  4. Codeforces 1082 毛毛虫图构造&最大权闭合子图

    A #include<bits/stdc++.h> using namespace std; typedef long long ll; , MAXM = ; //int to[MAXM ...

  5. Java运行环境绿色部署配置

    这个Java的绿色安装配置,还有从未自己的使用电脑说起来. 最近电脑运行慢,很长时间没有清理及维护了,而且有可能中毒或木马了,所以就把系统进行了Ghost还原了,所以原来安装的jdk环境也无法使用了, ...

  6. git生成公钥public key并添加SSH key。git乌龟gerrit下推送git【server sent :publickey】

    一.key 码云链接:http://git.mydoc.io/?t=180845#text_180845 博客链接: 方式一:https://blog.csdn.net/xb12369/article ...

  7. Web UI开发推荐!Kendo UI for jQuery自定义小部件——处理事件

    Kendo UI for jQuery最新试用版下载 Kendo UI目前最新提供Kendo UI for jQuery.Kendo UI for Angular.Kendo UI Support f ...

  8. JAVA 日期操作

    1.用java.util.Calender来实现 Calendar calendar=Calendar.getInstance(); calendar.setTime(new Date()); Sys ...

  9. Chrome报错提示Unchecked runtime.lastError: The message port closed before a response was received.

    经过查询,此错误是Chrome扩展插件引起的.由于Chrome修改了API接口,原来的请求被拦截.(Chrome 73 onwards disallows cross-origin requests ...

  10. jpa介绍

    1.jpa的介绍 JPA是Java Persistence API的简称, 中文名为Java持久层API; 是JDK 5.0注解或XML描述对象-关系表的映射关系, 并将运行期的实体对象持久化到数据库 ...