alibaba / fastjson

FASTJSON 2.0.x has been released, faster and more secure, recommend you upgrade.
https://github.com/alibaba/fastjson2/wiki/fastjson_1_upgrade_cn
Apache License 2.0
25.76k stars 6.5k forks source link

JSON.toJSONString自动过滤null值对应的字段 #3428

Open Yangshuixiang opened 4 years ago

Yangshuixiang commented 4 years ago

public class TestFastJson { public static void main(String[] args) { Map<java.lang.String, Object> email = new HashMap<>(); email.put("toArray", new String[]{"587129955","191519"}); email.put("ccArray", null); email.put("subject", "消灭复仇者联盟"); email.put("sponsor", "灭霸"); email.put("meetingRoom", "斯坦尔星球"); email.put("startTime", "2020-08-10 12:00:00"); email.put("endTime", "2020-08-10 12:30:00"); email.put("changeReason", "会议邀请!"); String jsonString1 = JSON.toJSONString(email); // Gson gson = new Gson(); // String jsonString1 = gson.toJson(email); System.out.println(jsonString1); } } 打印: {"sponsor":"灭霸","meetingRoom":"斯坦尔星球","changeReason":"会议邀请!","subject":"消灭复仇者联盟","toArray":["587129955","191519"],"startTime":"2020-08-10 12:00:00","endTime":"2020-08-10 12:30:00"}

少了ccArray

能不能保留这个null值对应的字段而不是直接过滤掉?

JiwenWu commented 4 years ago

多看看API吧 System.out.println(JSON.toJSONString(map, SerializerFeature.WRITE_MAP_NULL_FEATURES));