- 简介 (Introduction):
- 背景
json字符串返回的需要"",但是却是null,怎么处理呢,如下 - 结构图
1 [ 2 { 3 "1":{ 4 "age":"", 5 "id":"10086", 6 "userName":"zhangsan" 7 }, 8 "2":{ 9 "age":"", 10 "id":"", 11 "userName":"" 12 }, 13 "3":null 14 } 15 ]
需要转化为
1 { 2 "1":{ 3 "age":"", 4 "id":"10086", 5 "userName":"zhangsan" 6 }, 7 "2":{ 8 "age":"", 9 "id":"", 10 "userName":"" 11 }, 12 "3":"" 13 }
- 背景
-
核心
采用过滤模式,过滤到为null的对象,将其判断返回成""-
快速上手(Getting Started)
实体对象1 public class User { 2 3 private String id; 4 private String userName; 5 private String age; 6 7 public String getId() { 8 return id; 9 } 10 11 public void setId(String id) { 12 this.id = id; 13 } 14 15 public String getUserName() { 16 return userName; 17 } 18 19 public void setUserName(String userName) { 20 this.userName = userName; 21 } 22 23 24 public String getAge() { 25 return age; 26 } 27 28 public void setAge(String age) { 29 this.age = age; 30 } 31 }
多种方式测试
1、JSONArray.fromObject(jsonMap)
2、JSON.toJSONString(jsonMap)
3、JSONObject.toJSONString(jsonMap)1 import com.alibaba.fastjson.JSON; 2 import com.alibaba.fastjson.JSONObject; 3 import com.alibaba.fastjson.serializer.ValueFilter; 4 import com.mrliu.bean.User; 5 import net.sf.json.JSONArray; 6 7 import java.util.HashMap; 8 import java.util.Map; 9 10 public class TestJsonNullQuestion { 11 12 13 public static void main(String[] args) { 14 15 16 User user = new User(); 17 18 user.setId("10086"); 19 user.setUserName("zhangsan"); 20 21 User user1 = new User(); 22 23 Map<String, Object> jsonMap = new HashMap<>(); 24 25 26 jsonMap.put("1", user); 27 jsonMap.put("2", user1); 28 jsonMap.put("3", null); 29 30 31 System.out.println(JSONArray.fromObject(jsonMap)); 32 System.out.println(JSON.toJSONString(jsonMap)); 33 System.out.println(JSONObject.toJSONString(jsonMap)); 34 35 36 /** 37 * 过滤器,发现传入的是null时,转化为"" 38 */ 39 ValueFilter filter = new ValueFilter() { 40 @Override 41 public Object process(Object obj, String s, Object v) { 42 if (v == null) 43 return ""; 44 return v; 45 } 46 }; 47 48 // 添加过滤器 49 System.out.println(JSONObject.toJSONString(jsonMap, filter)); 50 } 51 52 53 }
-
-
环境设置 (Prerequisite):
- 环境
JDK1.8 - 配置
IDEA编辑 -
存在问题
暂无
- 环境
-
进阶篇 (Advanced):
研究中 ......