杰克逊序列化:忽略空值(或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 热门回答(190 赞)

你有一个错误的注释 - 它需要在类,而不是字段。即:

@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);即可

(为了记录,我认为这个答案的受欢迎程度表明这个注释应该适用于逐场* ahem @fastxml *)


#2 热门回答(40 赞)

你还可以设置全局选项:

objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

#3 热门回答(14 赞)

你也可以尝试使用

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)

如果你正在使用版本低于2(1.9.5)的杰克逊进行测试,我测试了它,你可以轻松地在课程上方使用此注释。不是为属性指定的,仅用于类去除。