Java通过递归方式校验json格式中null值以及去除为null的字段

描述

在java开发中,如果json对象(对象里面包含对象)中包含null值,会导致在转换使用时抛出net.sf.json.JSONException: object is null。

可以使用递归的方式判断json对象null值的存在

  1. 判断json对象是否包含null值
@SuppressWarnings({
      "unused", "rawtypes", "unchecked" })
	public static boolean isNullJson(JSONObject json) {
     
		String jsonStr = json.toString();
		if (jsonStr == null || jsonStr.equals("") || jsonStr.equals("null")) {
     
			return true;
		}
		if (jsonStr.indexOf("[") == 0) {
     
			List<Object> lists = new ArrayList<Object>();
			List<HashMap> list = JSON.parseArray(jsonStr, HashMap.class);
			for (int i = 0; i < list.size(); i++) {
     
				Map<String, Object> map = list.get(i);
				for (Map.Entry<String, Object> entrys : map.entrySet()) {
     
					if (entrys.getValue() == null || "".equals(entrys.getValue())) {
     
						return true;
					}
				}
			}
			return false;
		}
		if (jsonStr.indexOf("{") == 0) {
     
			LinkedHashMap<String, Object> jsonMap = JSON.parseObject(jsonStr,
					new TypeReference<LinkedHashMap<String, Object>>() {
     
					});
			for (Map.Entry<String, Object> entry : jsonMap.entrySet()) {
     
				if (entry.getValue() == null)
					return true;
			}
		}
		return false;
	}
  1. 去除json对象中的null值字段
@SuppressWarnings({
      "rawtypes", "unchecked" })
	public static Object filterNone(String jsonStr) throws Exception {
     
		if (jsonStr == null || jsonStr.equals("") || jsonStr.equals("null"))
			return null;
		if (jsonStr.indexOf("[") == 0) {
     
			List<Object> lists = new ArrayList<Object>();
			List<HashMap> list = JSON.parseArray(jsonStr, HashMap.class);
			for (int i = 0; i < list.size(); i++) {
     
				Map<String, Object> map = list.get(i);
				for (Map.Entry<String, Object> entrys : map.entrySet()) {
     
					Map<String, Object> maps = new HashMap<String, Object>();
					Object objs = JsonUtilO.filterNone(entrys.getValue().toString());
					if (objs != null) {
     
						maps.put(entrys.getKey(), objs);
						lists.add(maps);
					}
				}
			}
			if (lists.size() == 0) {
     
				return null;
			}
			return lists;
		}
		if (jsonStr.indexOf("{") == 0) {
     
			Map<String, Object> targetMap = new HashMap<String, Object>();
			LinkedHashMap<String, Object> jsonMap = JSON.parseObject(jsonStr,
					new TypeReference<LinkedHashMap<String, Object>>() {
     
					});
			for (Map.Entry<String, Object> entry : jsonMap.entrySet()) {
     
				Object obj = JsonUtilO.filterNone(entry.getValue().toString());
				if (obj == null)
					continue;
				targetMap.put(entry.getKey(), obj);
			}
			if (targetMap.isEmpty())
				return null;
			return targetMap;
		}
		return jsonStr;
	}

实际开发中用到,仅做记录!

你可能感兴趣的:(Java,软件开发,分布式微服务)