Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializate only certain JSON tags with Jackson

Is there a way that I dont have to extract the tags I need "manually" from the JSON if I don't want to deserialize all of them so that I can use this constructor?

public class Tweet {
    public String username;
    public String message;
    public String image_url;

    @JsonCreator
    public Tweet(
            @JsonProperty("from_user")          String username,
            @JsonProperty("text")               String message,
            @JsonProperty("profile_image_url")  String url) {
        this.username = username;
        this.message = message;
        this.image_url = url;
    }
}

And here it is the JSON:

   {
         "created_at":"Wed, 15 Aug 2012 18:17:55 +0000",
         "from_user":"felix_panda",
         "from_user_id":132396774,
         "from_user_id_str":"132396774",
         "from_user_name":"felix suganda",
         "geo":null,
         "id":235802515571101696,
         "id_str":"235802515571101696",
         "iso_language_code":"en",
         "metadata":{
            "result_type":"recent"
         },
         "profile_image_url":"http:\/\/a0.twimg.com\/profile_images\/2393214158\/profile_normal.jpg",
         "profile_image_url_https":"https:\/\/si0.twimg.com\/profile_images\/2393214158\/profile_normal.jpg",
         "source":"<a href="http:\/\/www.tweetcaster.com" rel="nofollow">TweetCaster for Android<\/a>",
         "text":"@Android how do u fix you lost your data connection because you left home network with data roaming (cont) http:\/\/t.co\/4coRjaXT",
     "to_user":"Android",
     "to_user_id":382267114,
     "to_user_id_str":"382267114",
     "to_user_name":"Android"

This is the error I get when deserializing it:

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "created_at"
like image 713
dinigo Avatar asked Aug 16 '12 17:08

dinigo


2 Answers

It looks like you want to disable FAIL_ON_UNKNOWN_PROPERTIES.

like image 137
Programmer Bruce Avatar answered Nov 12 '22 12:11

Programmer Bruce


I am using MongoJack. Here is what I did to solve it.

    ObjectMapper mapper = new ObjectMapper().setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    MongoJackModule.configure(mapper);
    JacksonDBCollection<Message, Long> coll = JacksonDBCollection.wrap(dbCollection, Message.class, Long.class, mapper);
like image 25
angelokh Avatar answered Nov 12 '22 12:11

angelokh