com.alibaba.fastjson
引入依赖包
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.9</version>
</dependency>
直接上最终代码
package yyst.myTest.jsonTest;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ValueFilter;
public class FjTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Map < String , Object > jsonMap = new HashMap< String , Object>();
jsonMap.put("c", "21");
jsonMap.put("d", "");
jsonMap.put("e", null);
System.out.println(JSONObject.toJSONString(jsonMap));
System.out.println(JSONObject.toJSONString(new FjBean()));
System.out.println();
System.out.println(JSONObject.toJSONString(jsonMap, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty));
System.out.println(JSONObject.toJSONString(new FjBean(), SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty));
System.out.println();
ValueFilter valueFilter = new ValueFilter() {
@Override
public Object process(Object object, String name, Object value) {
// TODO Auto-generated method stub
// System.out.println(object);
// System.out.println(name);
// System.out.println(value);
return value == null ? "" : value;
}
};
System.out.println(JSONObject.toJSONString(jsonMap, valueFilter));
System.out.println("\r\nstring to object");
System.out.println(JSONObject.parseObject(JSONObject.toJSONString(jsonMap, valueFilter), Map.class));
System.out.println(JSONObject.parseObject(JSONObject.toJSONString(new FjBean(), SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty), FjBean.class));
}
}
class FjBean{
public String a1 = "a";
public String a2 = null;
public String getA1() {
return a1;
}
public void setA1(String a1) {
this.a1 = a1;
}
public String getA2() {
return a2;
}
public void setA2(String a2) {
this.a2 = a2;
}
}
输出
{"c":"21","d":""}
{"a1":"a"}
{"c":"21","d":"","e":null}
{"a1":"a","a2":""}
{"c":"21","d":"","e":""}
string to object
{c=21, d=, e=}
yyst.myTest.jsonTest.FjBean@15615099
特别说明一下null值的处理。默认情况下,如果值为null,将不会输出。这在与其它语言的交互中非常容易出现bug。根据个人经验,转成空字符串可以适应更多的场景。上面代码中,通过加入SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty
,可以处理bean的情况。
但是当处理对象为Map时,无法正确转换。网上有不少Map处理的示例,但是都无法重现,有可能是版本问题,因为我在1.2.9的源码中未发现相关处理(读的不全,如有错误欢迎指正)。因此使用了自定义过滤器的方法。
https://github.com/alibaba/fastjson/wiki/ContextValueFilter