Scott
Scott

Reputation: 705

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. The incoming object looks like: 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:

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. 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

Upvotes: 0

Views: 633

Answers (1)

ChocolateAndCheese
ChocolateAndCheese

Reputation: 989

You can use the @JsonCreator annotation on a constructor like this:

@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.

Upvotes: 2

Related Questions