本文共 13203 字,大约阅读时间需要 44 分钟。
JSONObject.toJSONString(Object object, SerializerFeature... features)
SerializerFeature有用的一些枚举值
QuoteFieldNames———-输出key时是否使用双引号,默认为true
WriteMapNullValue——–是否输出值为null的字段,默认为false WriteNullNumberAsZero—-数值字段如果为null,输出为0,而非null WriteNullListAsEmpty—–List字段如果为null,输出为[],而非null WriteNullStringAsEmpty—字符类型字段如果为null,输出为”“,而非null WriteNullBooleanAsFalse–Boolean字段如果为null,输出为false,而非nullSerializerFeature.DisableCircularReferenceDetect ,如果没有设置这个参数会出现的问题:
如果对象中两个字段存放的是相同的List 对象,则会出现这种情况http://www.cnblogs.com/softidea/p/5873277.htmlListjobs = recommendJobBO.getJobs(); resultResVO.setModern(jobs); resultResVO.setTraditional(jobs);
Converter中FastJson的配置:
@Override public void configureMessageConverters(List> converters) { FastJsonHttpMessageConverter httpMessageConverter = new FastJsonHttpMessageConverter(); FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.QuoteFieldNames, SerializerFeature.WriteEnumUsingToString, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteDateUseDateFormat); fastJsonConfig.setSerializeFilters((ValueFilter) (o, s, source) -> { if (source == null) { return ""; } if (source instanceof Date) { return ((Date) source).getTime(); } return source; }); httpMessageConverter.setFastJsonConfig(fastJsonConfig); converters.add(httpMessageConverter); }
解决办法:
@Override public void configureMessageConverters(List> converters) { FastJsonHttpMessageConverter httpMessageConverter = new FastJsonHttpMessageConverter(); FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.QuoteFieldNames, SerializerFeature.WriteEnumUsingToString, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteDateUseDateFormat, SerializerFeature.DisableCircularReferenceDetect); fastJsonConfig.setSerializeFilters((ValueFilter) (o, s, source) -> { if (source == null) { return ""; } if (source instanceof Date) { return ((Date) source).getTime(); } return source; }); httpMessageConverter.setFastJsonConfig(fastJsonConfig); converters.add(httpMessageConverter); }
上面的SerializerFeature主要是针对Object对象序列化转换时的情况(这个时候才能判断参数的类型),而在Map中,你放进入了null就是null,进行序列化时已经没法判断它原来的类型了,所以并没有起作用。要使用SerializerFeature里相关null的参数,应该传入对象进行序列化。
对规则的理解:
SerializerFeature.WriteMapNullValue 是否输出值为null的字段,默认为false也就是说有null时会输出而不是忽略(默认策略是忽略,所以看不到为null的字段)
WriteNullStringAsEmpty—字符类型字段如果为null,输出为”“,而非null
注意是字段是字段是字段,而不是json.put("key",null),所以用它时,字段为null的可以转换为空字符串。如果让输出的json中所有为null的字符串都变成空字符串,最简单的做法就是加一个值过滤器,这样就避免了有的字段为null,有的字段为空字符的现象。
示例代码
import java.util.ArrayList;import java.util.HashMap;import java.util.HashSet;import java.util.List;import java.util.Map;import java.util.Set;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;import com.alibaba.fastjson.serializer.SerializerFeature;import com.alibaba.fastjson.serializer.ValueFilter;public class Demo1 { public class Student { private String name; private int age; private boolean isMale; private Student gf; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public boolean isMale() { return isMale; } public void setMale(boolean isMale) { this.isMale = isMale; } public Student getGf() { return gf; } public void setGf(Student gf) { this.gf = gf; } } private static ValueFilter filter = new ValueFilter() { @Override public Object process(Object obj, String s, Object v) { if (v == null) return ""; return v; } }; public static void main(String[] args) { new Demo1().foo(); new Demo1().bar(); } private void foo() { System.out.println("foo()---------------------------"); JSONObject j1 = new JSONObject(); j1.put("name", "zhangsan"); j1.put("age", 13); j1.put("isMale", true); j1.put("gf", null); Mapfav = new HashMap (); Set books = new HashSet (); books.add("三国"); books.add("史记"); fav.put("history", books); String[] arts = new String[] {}; fav.put("arts", arts); String[] musics = new String[] { "北京欢迎你", "画心" }; fav.put("musics", musics); List sports = new ArrayList (); fav.put("sports", sports); j1.put("fav", fav); List classmates = new ArrayList (); classmates.add(new Student()); Student lisi = new Student(); lisi.setMale(false); lisi.setAge(11); classmates.add(lisi); Student zhangsan = new Student(); zhangsan.setAge(13); zhangsan.setName("张三"); zhangsan.setMale(true); zhangsan.setGf(lisi); classmates.add(zhangsan); j1.put("classmates", classmates); String str = null; j1.put("str", str); System.out.println(j1.toString()); System.out .println(JSON.toJSONString(j1, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty)); System.out.println( JSON.toJSONString(j1, filter, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty)); System.out.println(JSON.toJSONString(j1, SerializerFeature.WriteNullStringAsEmpty)); System.out.println(JSON.toJSONString(j1, filter, SerializerFeature.WriteNullStringAsEmpty)); Map m = new HashMap (); m.put("key", j1); System.out.println( JSON.toJSONString(m, SerializerFeature.WriteNonStringKeyAsString, SerializerFeature.WriteNullStringAsEmpty)); System.out.println(JSON.toJSONString(m, filter, SerializerFeature.WriteNonStringKeyAsString, SerializerFeature.WriteNullStringAsEmpty)); } private void bar() { System.out.println("bar()---------------------------"); Student zhangsan = new Student(); zhangsan.setAge(13); zhangsan.setName("张三"); zhangsan.setMale(true); Student lisi = new Student(); // lisi.setName("lisi"); lisi.setMale(false); lisi.setAge(11); zhangsan.setGf(lisi); System.out.println( JSON.toJSONString(zhangsan, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty)); System.out.println(JSON.toJSONString(zhangsan, SerializerFeature.WriteMapNullValue)); System.out.println(JSON.toJSONString(zhangsan, SerializerFeature.WriteNullStringAsEmpty)); System.out.println(JSON.toJSONString(zhangsan)); System.out.println(JSON.toJSONString(zhangsan, filter)); System.out.println(JSON.toJSONString(zhangsan, filter, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty)); }}
foo()---------------------------{"isMale":true,"name":"zhangsan","classmates":[{"age":0,"male":false},{"age":11,"male":false},{"age":13,"gf":{"$ref":"$.classmates[1]"},"male":true,"name":"张三"}],"fav":{"sports":[],"musics":["北京欢迎你","画心"],"history":["史记","三国"],"arts":[]},"age":13}{"str":null,"isMale":true,"name":"zhangsan","classmates":[{"age":0,"gf":null,"male":false,"name":""},{"age":11,"gf":null,"male":false,"name":""},{"age":13,"gf":{"$ref":"$.classmates[1]"},"male":true,"name":"张三"}],"fav":{"sports":[],"musics":["北京欢迎你","画心"],"history":["史记","三国"],"arts":[]},"age":13,"gf":null}{"str":"","isMale":true,"name":"zhangsan","classmates":[{"age":0,"gf":"","male":false,"name":""},{"age":11,"gf":"","male":false,"name":""},{"age":13,"gf":{"$ref":"$.classmates[1]"},"male":true,"name":"张三"}],"fav":{"sports":[],"musics":["北京欢迎你","画心"],"history":["史记","三国"],"arts":[]},"age":13,"gf":""}{"isMale":true,"name":"zhangsan","classmates":[{"age":0,"male":false},{"age":11,"male":false},{"age":13,"gf":{"$ref":"$.classmates[1]"},"male":true,"name":"张三"}],"fav":{"sports":[],"musics":["北京欢迎你","画心"],"history":["史记","三国"],"arts":[]},"age":13}{"str":"","isMale":true,"name":"zhangsan","classmates":[{"age":0,"gf":"","male":false,"name":""},{"age":11,"gf":"","male":false,"name":""},{"age":13,"gf":{"$ref":"$.classmates[1]"},"male":true,"name":"张三"}],"fav":{"sports":[],"musics":["北京欢迎你","画心"],"history":["史记","三国"],"arts":[]},"age":13,"gf":""}{"key":{"isMale":true,"name":"zhangsan","classmates":[{"age":0,"male":false},{"age":11,"male":false},{"age":13,"gf":{"$ref":"$.key.classmates[1]"},"male":true,"name":"张三"}],"fav":{"sports":[],"musics":["北京欢迎你","画心"],"history":["史记","三国"],"arts":[]},"age":13}}{"key":{"str":"","isMale":true,"name":"zhangsan","classmates":[{"age":0,"gf":"","male":false,"name":""},{"age":11,"gf":"","male":false,"name":""},{"age":13,"gf":{"$ref":"$.key.classmates[1]"},"male":true,"name":"张三"}],"fav":{"sports":[],"musics":["北京欢迎你","画心"],"history":["史记","三国"],"arts":[]},"age":13,"gf":""}}bar()---------------------------{"age":13,"gf":{"age":11,"gf":null,"male":false,"name":""},"male":true,"name":"张三"}{"age":13,"gf":{"age":11,"gf":null,"male":false,"name":null},"male":true,"name":"张三"}{"age":13,"gf":{"age":11,"male":false},"male":true,"name":"张三"}{"age":13,"gf":{"age":11,"male":false},"male":true,"name":"张三"}{"age":13,"gf":{"age":11,"gf":"","male":false,"name":""},"male":true,"name":"张三"}{"age":13,"gf":{"age":11,"gf":"","male":false,"name":""},"male":true,"name":"张三"}
JsonPathTestData.json
{ "store": { "book": [ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": 8.95 }, { "category": "fiction", "author": "Evelyn Waugh", "title": "Sword of Honour", "price": 12.99, "isbn": "0-553-21311-3" } ], "bicycle": { "color": "red", "price": 19.95 } }}
@Test public void testJsonPath() throws IOException { InputStream resourceAsStream = this.getClass().getResourceAsStream("/JsonPathTestData.json"); String jsonStr = IOUtils.toString(resourceAsStream, "utf-8"); System.out.println(jsonStr); System.out.println(jsonStr); JSONObject jsonObject = JSON.parseObject(jsonStr); System.out.println("\nBook数目:" + JSONPath.eval(jsonObject, "$.store.book.size()")); System.out.println("第一本书title:" + JSONPath.eval(jsonObject, "$.store.book[0].title")); System.out.println("price大于10元的book:" + JSONPath.eval(jsonObject, "$.store.book[price > 10]")); System.out.println("price大于10元的title:" + JSONPath.eval(jsonObject, "$.store.book[price > 10][0].title")); System.out.println("category(类别)为fiction(小说)的book:" + JSONPath.eval(jsonObject, "$.store.book[category = 'fiction']")); System.out.println("bicycle的所有属性值" + JSONPath.eval(jsonObject, "$.store.bicycle.*")); System.out.println("bicycle的color和price属性值" + JSONPath.eval(jsonObject, "$.store.bicycle['color','price']")); } @Test public void testGenerics() { Resultresult = new Result<>(); result.setMsg("Success"); List users = new ArrayList<>(); users.add(new User(1L, "Name1")); users.add(new User(2L, "Name2")); result.setModule(users); String js = JSON.toJSONString(result); System.out.println(js); //java.lang.ClassCastException: com.alibaba.fastjson.JSONObject cannot be cast to com.tangcheng.learning.json.User// Result obj = (Result ) JSON.parseObject(js, Result.class); Result userResult = JSON.parseObject(js, new TypeReference >() { }); System.out.println(userResult); }
public class User { private Long id; private String name; public User() { } public User(Long id, String name) { this.id = id; this.name = name; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + '}'; }}
import java.util.List;public class Result{ private String msg; private List module; public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public List getModule() { return module; } public void setModule(List module) { this.module = module; } @Override public String toString() { return "Result{" + "msg='" + msg + '\'' + ", module=" + module + '}'; }}
https://www.slideshare.net/randfish/inside-googles-numbers-in-2017?next_slideshow=1