最佳答案
我目前使用的是 jackson2.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,但它也不起作用!谢谢你们的帮助!