在java开发中,大家经常会遇到把一个对象转换成string问题,一般用到的几种方式toString,强制转换(String),String.valueOf这三种方式,但具体这三种方式有什么区别,大家知道吗?由于这个不是本文讨论的重点,找个篇博客,写的挺简单易懂的,不太清楚的大家可以看一下
链接:https://blog.csdn.net/sunzhenhua0608/article/details/8014060
上面说了那么多废话,现在我们开始讨论本博客的主题"对象转string与jsonString的区别"
先说区别:
在实现方面看:jsonString是通过流的方字打印出文本字符串,在String类型进行操作的时候会拆分为char类型循环添加\\来防止转译字符转译的,不同的类型会做不同的预处理,java的toStirng一般都是拼接的字符串,无特殊预处理
外管上看:jsonString在按照文本一模一样打印的,如果只实例化了对象,对象本身没有默认值的情况下返回 {}; string是对对象进行拼接操作,会按照java规范进行转移等编译
jsonString 代码分析:使用的jar包 alibaba.fastjson
调用转源码包的过程
//json转string方法,JSON.toJSONString(object)
public static String toJSONString(Object object) {
return toJSONString(object);
}
//实际处理类
public static String toJSONString(Object object, SerializerFeature... features) {
//继承了Writer
SerializeWriter out = new SerializeWriter();
try {
//
JSONSerializer serializer = new JSONSerializer(out);
SerializerFeature[] var4 = features;
int var5 = features.length;
for(int var6 = 0; var6 < var5; ++var6) {
SerializerFeature feature = var4[var6];
serializer.config(feature, true);
}
serializer.write(object);
String var11 = out.toString();
return var11;
} finally {
out.close();
}
}
public final void write(Object object) {
if (object == null) {
this.out.writeNull();
} else {
Class<?> clazz = object.getClass();
//根据object的类型,走不同的实例化类
ObjectSerializer writer = this.getObjectWriter(clazz);
try {
//writer对象的
writer.write(this, object, (Object)null, (Type)null, 0);
} catch (IOException var5) {
throw new JSONException(var5.getMessage(), var5);
}
}
public final void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
SerializeWriter out = serializer.getWriter();
if (object == null) {
if (out.isEnabled(SerializerFeature.WriteNullListAsEmpty)) {
out.write("[]");
} else {
out.writeNull();
}
} else {
Object[] array = (Object[])((Object[])object);
int size = array.length;
SerialContext context = serializer.getContext();
serializer.setContext(context, object, fieldName, 0);
try {
out.append('[');
for(int i = 0; i < size; ++i) {
if (i != 0) {
out.append(',');
}
Object item = array[i];
if (item == null) {
out.append("null");
} else if (item.getClass() == this.componentType) {
this.compObjectSerializer.write(serializer, item, i, (Type)null, 0);
} else {
ObjectSerializer itemSerializer = serializer.getObjectWriter(item.getClass());
itemSerializer.write(serializer, item, i, (Type)null, 0);
}
}
out.append(']');
} finally {
serializer.setContext(context);
}
}
}