私は現在jackson 2.1.4を使用していますが、オブジェクトをJSON文字列に変換するときにフィールドを無視するのに問題があります。ここでジャクソンのシリアル化:空の値を無視する(またはnull)
は、変換する対象として働き私のクラスです:
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"}
することができます私はそれらのヌル値を避けますか?私は "購読"目的のために必要な情報を取ってみたい!
はここでまさに私が探しているの出力です:私も@JsonInclude(Include.NON_NULL)を試み、nullにすべての私の変数を置く
{"data":{"username":"Vincent","password":"test"},"requestType":"login"}
が、それはどちらか動作しませんでした!助けてくれてありがとう!
実際にはinclude.NON_NULLアノテーションを機能させる方法はありませんか?またはNON_EMTPYのもの? 私はどちらがnullになるのか知っているので、状況によって異なります。私はシリアル化/デシリアライズしたいすべてのオブジェクトに対して同じ "JsonOperation"クラスを使用していますが、状況に応じて使用する必要がある変数のみを初期化しています。これを行うには良い方法ですか、必要な変数のみを含むseveralsクラスを実行する必要があります(ヌル/空の変数は決してないので、アノテーションを使用する必要はありません) – Shinnyx
ああ、申し訳ありません、私今起こっていることを見てください。私の編集された答えを見てください。 – drewmoore
これは機能しています!私はそれが問題だとは信じられません...ドリューモアありがとう! – Shinnyx