JSONObject中Java对象转换成Json格式的两种方式

1、alibaba的JSONObject对象调用toJSONString方法直接转换

pom.xml 依赖:

<dependency>
   <groupId>com.alibabagroupId>
    <artifactId>fastjsonartifactId>
    <version>1.2.41version>
dependency>

代码:

RiemannUser riemannUser = new RiemannUser();
riemannUser.setId(1);
riemannUser.setMessage("Hello JSONObject");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = sdf.format(new Date());
riemannUser.setSendDate(date);

String jsonString = JSONObject.toJSONString(riemannUser);
System.out.println(jsonString);

运行结果:

{"id":1,"message":"Hello JSONObject","sendDate":"2019-07-04 00:01:55"}

alibaba的JSONObject.toJSONString 的源码

public static String toJSONString(Object object) {
	return toJSONString(object, new SerializerFeature[0]);
}

public static String toJSONString(Object object, SerializerFeature... features) {
    SerializeWriter out = new SerializeWriter();

    try {
        JSONSerializer serializer = new JSONSerializer(out);
        for (com.alibaba.fastjson.serializer.SerializerFeature feature : features) {
            serializer.config(feature, true);
        }

        serializer.write(object);

        return out.toString();
    } finally {
        out.close();
    }
}

2、net.sf.json.JSONObject 先调用 fromObject 再调用 toString

pom.xml 依赖:

<dependency>
    <groupId>net.sf.json-libgroupId>
    <artifactId>json-libartifactId>
    <version>2.4version>
    <classifier>jdk15classifier>
dependency>

这里一定要加入jdk15 这一行,原因是:还关系到两个jdk版本的实现json-lib-2.1-jdk13.jar和json-lib-2.1-jdk15.jar。

代码:

RiemannUser riemannUser = new RiemannUser();
riemannUser.setId(1);
riemannUser.setMessage("Hello JSONObject");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = sdf.format(new Date());
riemannUser.setSendDate(date);

JSONObject jsonObject = JSONObject.fromObject(riemannUser);
String jsonString = jsonObject.toString();
System.out.println(jsonString);

运行结果:

{"id":1,"intList":[],"message":"Hello JSONObject","nodeName":"","sendDate":"2019-07-03 23:59:32"}

3、总结

通过这两种方式,不知道小伙伴们有没有发现什么秘密。

是的,运行结果不一样,第一种方式是得到set了的值,为空的值不会取出来。

相反,第二种方式得到是这个对象的所有属性,不管有值还是没有值。

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()) {
            throw new JSONException("'object' is an Annotation.");
        } else if (object instanceof 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) {
            return _fromJSONString((JSONString)object, jsonConfig);
        } else if (object instanceof 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);
            }
        } else {
            return new JSONObject();
        }
    } else {
        return new JSONObject(true);
    }
}

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);
    }
}

public JSONObject(boolean isNull) {
   this();
    this.nullObject = isNull;
}

JSONObject中Java对象转换成Json格式的两种方式_第1张图片

JSONObject中Java对象转换成Json格式的两种方式_第2张图片

从源码也可以看出,为空的字段,赋的空的值。

你可能感兴趣的:(Java)