我从其他服务中获取以下对象,我需要将其解析为服务中的POJO。传入对象看起来像: AddressMessage.java
public class AddressMessage {
@NotEmpty
@JsonProperty("id")
private String id;
@NotEmpty
@JsonProperty("address")
private String address;
public String getId() {
return this.id;
}
public String getAddress() {
return this.address;
}
@SuppressWarnings("unchecked")
@JsonProperty("data")
public void unpackNested(Map<String, Object> rawMessage) {
Map<String, String> data = (Map<String, String>) rawMessage.get("data");
this.id = (String) data.get("id");
this.address = (String) data.get("address");
}
}
,传入的数据如下:
{“data”: { “id” : “sampleId”, “address”: “sampleAddress” }}
我尝试将传入的json字符串解析为一个普通的Object,但这没用:
private void publishMessage(String rawMessage, AMQP.BasicProperties props) throws IOException {
Object json = objectMapper.readValue(rawMessage, Object.class);
log.debug(objectMapper.writeValueAsString(json));
我还尝试接受原始消息,并使用对象映射器将其直接映射到类,如下所示:
private void publishMessage(String rawMessage, AMQP.BasicProperties props) throws IOException {
AddressMessage addressMessage = objectMapper.readValue(rawMessage,
AddressMessage.class);
}
上述代码的异常:
Unexpected character ('“' (code 8220 / 0x201c)): was expecting double-quote to start field name
我想从对象中拉出“ id”和“ address”属性,但是由于解析错误,我一直遇到异常。一些指导将不胜感激,谢谢!
添加:我目前未使用“ unpackNested”方法,但我认为我会把它扔在那里,以防引发任何想法
答案 0 :(得分:2)
您可以在像这样的构造函数上使用@JsonCreator
批注:
@JsonCreator
public AddressMessage(@JsonProperty("data") Map<String, Object> rawJson) {
this.id = rawJson.get("id").toString();
this.address = rawJson.get("address").toString();
}
这告诉杰克逊在反序列化时使用该构造函数。