项目中经常用到JsonObject或JsonArray来转化接口返回,有些Null值就在转化过程中被过滤掉,怎么才能不被过滤?

1.新建一个JsonFilter类(将接口返回的Null值替换为" ")

@Data
public class JsonFilter implements ValueFilter {

    @Override
    public Object process(Object o, String s, Object v) {
        if (v == null) {
            return "";
        }
        return v;
    }
}

2.实际转化过程中使用,Object或其他类型数据转Json字符串时,使用Json过滤。

public static void main(String[] args){
   List<Map<String,String>> list = new ArrayList<>();
   Map map1 = new HashMap(2);
   map1.put("caId","66217");
   map1.put("imgType",null);
   Map map2 = new HashMap(2);
   map2.put("caId","98504");
   map2.put("imgType",null);
   list.add(map1);
   list.add(map2);
   JSONArray jsonArray = JSON.parseArray(JSON.toJSONString(list,new JsonFilter()));
   JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(list.get(0),new JsonFilter()));
  //输出结果为[{"caId":"66217","imgType":""},{"caId":"98504","imgType":""}]
   System.out.println(jsonArray);
  //输出结果为{"caId":"66217","imgType":""}
   System.out.println(jsonObject);
    }

  还有一种方法是使用SerializerFeature,本来使用了WriteNullStringAsEmpty,但是没起作用(后面查找发现这个方法是字段,字段为null时,转化为" "),用WriteMapNullValue也勉强可以,但还是推荐使用加过滤器的方法。

    public static void main(String[] args){
        List<Map<String,String>> list = new ArrayList<>();
        Map map1 = new HashMap(2);
        map1.put("caId","66217");
        map1.put("imgType",null);
        Map map2 = new HashMap(2);
        map2.put("caId","98504");
        map2.put("imgType",null);
        list.add(map1);
        list.add(map2);
//输出结果是[{"caId":"66217","imgType":null},{"caId":"98504","imgType":null}]
System.out.println(JSON.toJSONString(list, SerializerFeature.WriteMapNullValue));
}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐