MarioC
MarioC

Reputation: 3228

Spring jackson - Map a json to a specific object field

i'm trying to deserialize a json string to match an object but i cannot do this with JSONProperties

This is my object

 public class Feedback{

    @JsonProperty("event_id")
    private long eventId;

    //getter and setter


    }

and the JSON string i get is

{..., "event_id":1111111111, ....}

When i deserialize the String into Feedback, eventId is just skipped...

I deserialize in this way

ObjectMapper mapper = new ObjectMapper();
Feedback feedback = mapper.readValue(json, Feedback);

I have also other fields in Feedback which have the same name of the json field, and they are mapped correctly obviously

Upvotes: 0

Views: 1690

Answers (2)

Manza
Manza

Reputation: 3527

This is a very common mistake. Be sure to use

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;

OR

import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.ObjectMapper;

Mixing the imports will result in issues.

First one is the new version, second one is the old version. Use the first one ;)

Upvotes: 0

cassiomolin
cassiomolin

Reputation: 130917

Annotate the getter instead of annotating the field:

public class Feedback {

    private long eventId;

    @JsonProperty("event_id")
    public long getEventId() {
        return eventId;
    }

    public void setEventId(long eventId) {
        this.eventId = eventId;
    }
}

Upvotes: 4

Related Questions