[英]Converting json string to generic Map using Jackson
I am getting the following object from a different service and I need to parse it into a POJO I have in my service. 我从其他服务获取以下对象,我需要将其解析为服务中拥有的POJO。 The incoming object looks like: AddressMessage.java
传入的对象看起来像: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");
}
}
and the incoming data looks like: 传入的数据如下所示:
{“data”: { “id” : “sampleId”, “address”: “sampleAddress” }}
I've tried parsing the incoming json string to a plain Object but that didn't work: 我已经尝试将传入的json字符串解析为一个普通的Object,但这没有用:
private void publishMessage(String rawMessage, AMQP.BasicProperties props) throws IOException {
Object json = objectMapper.readValue(rawMessage, Object.class);
log.debug(objectMapper.writeValueAsString(json));
I also tried taking in the raw message and mapping it directly to the class using the object mapper like this: 我还尝试接受原始消息,并使用对象映射器将其直接映射到类,如下所示:
private void publishMessage(String rawMessage, AMQP.BasicProperties props) throws IOException {
AddressMessage addressMessage = objectMapper.readValue(rawMessage,
AddressMessage.class);
}
Exception for above code: 以上代码的异常:
Unexpected character ('“' (code 8220 / 0x201c)): was expecting double-quote to start field name
I want to pull the "id" and "address" properties out of the object but I keep running into exception due to parsing errors. 我想从对象中提取“ id”和“ address”属性,但由于解析错误,我一直遇到异常。 Some guidance will be greatly appreciated, thanks!
一些指导将不胜感激,谢谢!
Addition: I am not currently using the "unpackNested" method but thought i'd throw it in there in case it sparks any idea 另外:我目前不使用“ unpackNested”方法,但我认为我会把它扔在那里,以防引发任何想法
You can use the @JsonCreator
annotation on a constructor like this: 您可以在像这样的构造函数上使用
@JsonCreator
批注:
@JsonCreator
public AddressMessage(@JsonProperty("data") Map<String, Object> rawJson) {
this.id = rawJson.get("id").toString();
this.address = rawJson.get("address").toString();
}
This tells Jackson to use that constructor when deserializing. 这告诉杰克逊在反序列化时使用该构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.