Jackson序列化:忽略空值(或null)

我当前正在使用杰克逊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();

}

这是输出:


{"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,但是它也不起作用!感谢您的帮助!


qq_遁去的一_1
浏览 6407回答 3
3回答

翻过高山走不出你

您将注解放置在错误的位置-注解必须在类上,而不是在字段上。即:@JsonInclude(Include.NON_NULL) //or Include.NON_EMPTY, if that fits your use case&nbsp;public static class Request {&nbsp; // ...}如注释中所述,在版本2.x +中,此注释的语法为:@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) // or JsonSerialize.Inclusion.NON_EMPTY另一个选择是ObjectMapper直接配置,只需调用 mapper.setSerializationInclusion(Include.NON_NULL);(根据记录,我认为此答案的流行程度表明该注释应逐字段应用* ahem @ fasterxml *)

慕仙森

您也可以尝试使用@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)如果您要测试我测试过的版本低于2+(1.9.5)的杰克逊,则可以在类上方轻松使用此注释。不是为属性指定的,只是为类定义的。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java