GVKun编程网logo

Jackson序列化:忽略空值(或null)(jackson序列化动态忽略字段)

13

在本文中,我们将给您介绍关于Jackson序列化:忽略空值的详细内容,并且为您解答或null的相关问题,此外,我们还将为您提供关于Jacksonjson序列化和反序列化工具类、jackson实体转js

在本文中,我们将给您介绍关于Jackson序列化:忽略空值的详细内容,并且为您解答或null的相关问题,此外,我们还将为您提供关于Jackson json序列化和反序列化工具类、jackson 实体转 json 为 NULL 或者为空不参加序列化、jackson 实体转 json 为 NULL 或者为空不参加序列化【转载】、jackson 实体转json 为NULL或者为空不参加序列化的知识。

本文目录一览:

Jackson序列化:忽略空值(或null)(jackson序列化动态忽略字段)

Jackson序列化:忽略空值(或null)(jackson序列化动态忽略字段)

我目前正在使用杰克逊2.1.4,并且在将对象转换为JSON字符串时忽略字段时遇到了一些麻烦。

这是我的类,它充当要转换的对象:

public class JsonOperation {public static class Request {    @JsonInclude(Include.NON_EMPTY)    String requestType;    Data data = new Data();    public static class Data {        @JsonInclude(Include.NON_EMPTY)        String username;        String email;        String password;        String birthday;        String coinsPackage;        String coins;        String transactionId;        boolean isLoggedIn;    }}public static class Response {    @JsonInclude(Include.NON_EMPTY)    String requestType = null;    Data data = new Data();    public static class Data {        @JsonInclude(Include.NON_EMPTY)        enum ErrorCode { ERROR_INVALID_LOGIN, ERROR_USERNAME_ALREADY_TAKEN, ERROR_EMAIL_ALREADY_TAKEN };        enum Status { ok, error };        Status status;        ErrorCode errorCode;        String expiry;        int coins;        String email;        String birthday;        String pictureUrl;        ArrayList <Performer> performer;    }}}

这是我如何转换它:

ObjectMapper mapper = new ObjectMapper();mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);JsonOperation subscribe = new JsonOperation();subscribe.request.requestType = "login";subscribe.request.data.username = "Vincent";subscribe.request.data.password = "test";Writer strWriter = new StringWriter();try {    mapper.writeValue(strWriter, subscribe.request);} catch (JsonGenerationException e) {    // TODO Auto-generated catch block    e.printStackTrace();} catch (JsonMappingException e) {    // TODO Auto-generated catch block    e.printStackTrace();} catch (IOException e) {    // TODO Auto-generated catch block    e.printStackTrace();}Log.d("JSON", strWriter.toString())

这是输出:

{"data":{"birthday":null,"coins":null,"coinsPackage":null,"email":null,"username":"Vincent","password":"test","transactionId":null,"isLoggedIn":false},"requestType":"login"}

如何避免这些空值?我只想获取“订阅”目的所需的信息!

这正是我要寻找的输出:

{"data":{"username":"Vincent","password":"test"},"requestType":"login"}

我还尝试了@JsonInclude(Include.NON_NULL)并将所有变量都设置为null,但是它也不起作用!感谢您的帮助!

答案1

小编典典

你将注解放置在错误的位置-注解必须在类上,而不是在字段上。即:

@JsonInclude(Include.NON_NULL) //or Include.NON_EMPTY, if that fits your use case public static class Request {  // ...}

如注释中所述,在2.x以下的版本中,此注释的语法为:

@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) // or JsonSerialize.Inclusion.NON_EMPTY

另一种选择是ObjectMapper直接配置,只需调用 mapper.setSerializationInclusion(Include.NON_NULL);

Jackson json序列化和反序列化工具类

Jackson json序列化和反序列化工具类

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;

/**
 * Jackson json序列化和反序列化工具类
 * Created by macro on 2018/4/26.
 */
public class JsonUtil {

    // 定义jackson对象
    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 将对象转换成json字符串。
     */
    public static String objectToJson(Object data) {
        try {
            String string = MAPPER.writeValueAsString(data);
            return string;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 将json结果集转化为对象
     * 
     * @param jsonData json数据
     * @param beanType 对象中的object类型
     */
    public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
        try {
            T t = MAPPER.readValue(jsonData, beanType);
            return t;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 将json数据转换成pojo对象list
     */
    public static <T>List<T> jsonToList(String jsonData, Class<T> beanType) {
        JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
        try {
            List<T> list = MAPPER.readValue(jsonData, javaType);
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return null;
    }
    
}

 

jackson 实体转 json 为 NULL 或者为空不参加序列化

jackson 实体转 json 为 NULL 或者为空不参加序列化

1. 实体上

@JsonInclude(Include.NON_NULL) 

// 将该标记放在属性上,如果该属性为 NULL 则不参与序列化 
// 如果放在类上边,那对这个类的全部属性起作用 
//Include.Include.ALWAYS 默认 
//Include.NON_DEFAULT 属性为默认值不序列化 
//Include.NON_EMPTY 属性为 空(“”) 或者为 NULL 都不序列化 
//Include.NON_NULL 属性为 NULL 不序列化 


2. 代码上
ObjectMapper mapper = new ObjectMapper();

mapper.setSerializationInclusion(Include.NON_NULL);  

// 通过该方法对 mapper 对象进行设置,所有序列化的对象都将按改规则进行系列化 
//Include.Include.ALWAYS 默认 
//Include.NON_DEFAULT 属性为默认值不序列化 
//Include.NON_EMPTY 属性为 空(“”) 或者为 NULL 都不序列化 
//Include.NON_NULL 属性为 NULL 不序列化 

User user = new User(1,"",null); 
String outJson = mapper.writeValueAsString(user); 
System.out.println(outJson);

 

注意:只对 VO 起作用,Map List 不起作用

例如

1

2

3

4

5

6

7

8

9

10

11

12

13

14

ObjectMapper mapper = new ObjectMapper();

mapper.setSerializationInclusion(Include.NON_NULL);

 

Map map = new HashMap();

map.put("a"null);

map.put("b""b");

 

String ret_val = mapper.writeValueAsString(map);

System.err.println(ret_val);

Map m = mapper.readValue(ret_val, Map.class);

System.err.println(m.get("a") + "|" + m.get("b"));

输出:

{"b":"b","a":null}

null|b

  

1

2

3

4

5

6

7

8

9

10

11

VO vo = new VO();

vo.setA(null);

vo.setB("b");

         

String ret_val1 = mapper.writeValueAsString(vo);

System.err.println(ret_val1);

VO v = mapper.readValue(ret_val1, VO.class);

System.err.println(v.getA() + "|" + v.getB());<br>

输出

{"b":"b"}

|b

jackson 实体转 json 为 NULL 或者为空不参加序列化【转载】

jackson 实体转 json 为 NULL 或者为空不参加序列化【转载】

OSC 请你来轰趴啦!1028 苏州源创会,一起寻宝 AI 时代

原博客:https://www.cnblogs.com/yangy608/p/3936848.html

 

1. 实体上

/**
 * 将该标记放在属性上,如果该属性为NULL则不参与序列化
 * 如果放在类上边,那对这个类的全部属性起作用
 * Include.Include.ALWAYS 默认
 * Include.NON_DEFAULT 属性为默认值不序列化
 * Include.NON_EMPTY 属性为 空(“”) 或者为 NULL 都不序列化
 * Include.NON_NULL 属性为NULL 不序列化
 */
@JsonInclude(Include.NON_NULL)

 

2. 代码上

ObjectMapper mapper = new ObjectMapper();

/**
 * 通过该方法对mapper对象进行设置,所有序列化的对象都将按改规则进行系列化 
 * Include.Include.ALWAYS 默认 
 * Include.NON_DEFAULT 属性为默认值不序列化 
 * Include.NON_EMPTY 属性为 空(“”) 或者为 NULL 都不序列化 
 * Include.NON_NULL 属性为NULL 不序列化 
 */
mapper.setSerializationInclusion(Include.NON_NULL);

User user = new User(1,"",null);
String outJson = mapper.writeValueAsString(user);
System.out.println(outJson);

 

注意:只对 VO 起作用,Map List 不起作用,例如:

ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
 
Map map = new HashMap();
map.put("a", null);
map.put("b", "b");
 
String ret_val = mapper.writeValueAsString(map);
System.err.println(ret_val);
Map m = mapper.readValue(ret_val, Map.class);
System.err.println(m.get("a") + "|" + m.get("b"));

输出:

{"b":"b","a":null}

null|b

 

VO vo = new VO();
vo.setA(null);
vo.setB("b");
         
String ret_val1 = mapper.writeValueAsString(vo);
System.err.println(ret_val1);
VO v = mapper.readValue(ret_val1, VO.class);
System.err.println(v.getA() + "|" + v.getB());<br>

输出:

{"b":"b"}

|b

 

 

 

 


 

 

jackson 实体转json 为NULL或者为空不参加序列化

jackson 实体转json 为NULL或者为空不参加序列化

 

1.实体上

@JsonInclude(Include.NON_NULL) 

//将该标记放在属性上,如果该属性为NULL则不参与序列化 
//如果放在类上边,那对这个类的全部属性起作用 
//Include.Include.ALWAYS 默认 
//Include.NON_DEFAULT 属性为默认值不序列化 
//Include.NON_EMPTY 属性为 空(“”) 或者为 NULL 都不序列化 
//Include.NON_NULL 属性为NULL 不序列化 


2.代码上
ObjectMapper mapper = new ObjectMapper();

mapper.setSerializationInclusion(Include.NON_NULL);  

//通过该方法对mapper对象进行设置,所有序列化的对象都将按改规则进行系列化 
//Include.Include.ALWAYS 默认 
//Include.NON_DEFAULT 属性为默认值不序列化 
//Include.NON_EMPTY 属性为 空(“”) 或者为 NULL 都不序列化 
//Include.NON_NULL 属性为NULL 不序列化 

User user = new User(1,"",null); 
String outJson = mapper.writeValueAsstring(user); 
System.out.println(outJson);

 

注意:只对VO起作用,Map List不起作用

例如

1
2
3
4
5
6
7
8
9
10
11
12
13
14
ObjectMapper mapper =  new  ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
 
Map map =  new  HashMap();
map.put( "a" null );
map.put( "b" "b" );
 
String ret_val = mapper.writeValueAsstring(map);
System.err.println(ret_val);
Map m = mapper.readValue(ret_val,Map. class );
System.err.println(m.get( "a" ) +  "|"  + m.get( "b" ));
输出:
{ "b" : "b" , "a" : null }
null |b

  

1
2
3
4
5
6
7
8
9
10
11
VO vo =  new  VO();
vo.setA( null );
vo.setB( "b" );
         
String ret_val1 = mapper.writeValueAsstring(vo);
System.err.println(ret_val1);
VO v = mapper.readValue(ret_val1,VO. class );
System.err.println(v.getA() +  "|"  + v.getB());<br>
输出
{ "b" : "b" }
|b

今天关于Jackson序列化:忽略空值或null的分享就到这里,希望大家有所收获,若想了解更多关于Jackson json序列化和反序列化工具类、jackson 实体转 json 为 NULL 或者为空不参加序列化、jackson 实体转 json 为 NULL 或者为空不参加序列化【转载】、jackson 实体转json 为NULL或者为空不参加序列化等相关知识,可以在本站进行查询。

本文标签: