Jackson シリアル化: 空の値 (または null) を無視する 質問する

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"}

これらの null 値を回避するにはどうすればよいでしょうか? 「サブスクリプション」の目的のために必要な情報のみを取得したいのです。

私が求めている出力はまさにこれです:

{"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

もう1つのオプションはObjectMapper、直接設定することです。mapper.setSerializationInclusion(Include.NON_NULL);

(記録のために言っておくと、この回答の人気は、この注釈がすべきフィールドごとに適用可能、@fasterxml)

おすすめ記事