我得到了这个转义的JSON
"{\"UniqueId\":[],\"CustomerOffers\":{},\"Success\":false,\"ErrorMessages\":[\"Test Message\"],\"ErrorType\":\"GeneralError\"}"
并且我需要使用Jackson将其转换为Java对象。
// https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind
compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.8'
我创建了班级
public class Data {
private List<UUID> UniqueId;
private Map<Integer, List<Integer>> CustomerOffers;
private Boolean Success;
private List<String> ErrorMessages;
private String ErrorType;
public List<UUID> getUniqueId() {
return this.UniqueId;
}
public void setUniqueId(List<UUID> uniqueId) {
this.UniqueId = uniqueId;
}
public Map<Integer, List<Integer>> getCustomerOffers() {
return this.CustomerOffers;
}
public void setCustomerOffers(Map<Integer, List<Integer>> customerOffers) {
this.CustomerOffers = customerOffers;
}
public Boolean getSuccess() {
return this.Success;
}
public void setSuccess(Boolean success) {
this.Success = success;
}
public List<String> getErrorMessages() {
return this.ErrorMessages;
}
public void setErrorMessages(List<String> errorMessages) {
this.ErrorMessages = errorMessages;
}
public String getErrorType() {
return this.ErrorType;
}
public void setErrorType(String errorType) {
this.ErrorType = errorType;
}
}
然后我创建了将其转换的方法
public class Deserializing {
public void processing(String input){
ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
String jsonInString = "\"{\"UniqueId\":[],\"CustomerOffers\":{},\"Success\":false,\"ErrorMessages\":[\"Test Message\"],\"ErrorType\":\"GeneralError\"}\"";
String newJSON = org.apache.commons.lang3.StringEscapeUtils.unescapeJava(jsonInString);
newJSON= newJSON.substring(1, jsonInString.length()-1);
try {
// JSON string to Java object
Data data = mapper.readValue(newJSON, Data.class);
System.out.println(data);
System.out.println("Get Success "+ data.getSuccess()); // return "false" if Data object is public ; null if private
System.out.println("Get UniqueID " + data.getUniqueId()); // return [] if Data object is public ; null if private
} catch (IOException e) {
e.printStackTrace();
}
}
}
Data类中设置为public的任何变量,那么当我调用getter时,都会得到the corresponding value
。无论Data类中的哪个变量设置为private,当我调用getter时,我都会得到null
。
字母和二传手总是公开的。
我想知道,如果ObjectMapper设置为私有对象,为什么不能映射该对象?我可以将其设置为公开,但这不是最佳实践。
感谢。
问题是,杰克逊将始终假定setSuccess
将用于success
字段,大写的字段名称需要@JsonProperty
支持。
类似物;
@JsonProperty
然后您将看到将值反序列化为Java对象;
public class Data {
@JsonProperty("UniqueId")
private List<UUID> UniqueId;
@JsonProperty("CustomerOffers")
private Map<Integer, List<Integer>> CustomerOffers;
@JsonProperty("Success")
private Boolean Success;
@JsonProperty("ErrorMessages")
private List<String> ErrorMessages;
@JsonProperty("ErrorType")
private String ErrorType;
}