Perry Hoekstra
Perry Hoekstra

Reputation: 69

Jackson Deserialization Issue

I have the following JSON I am receiving from a REST call:

"socialConnectionsData" : {
  "friends" : [ {
    "friend" : {
      "firstname" : "John",
      "lastname" : "Doe"
     }
    }]
}

My current class looks like this:

public class SocialConnectionsData {
private List<Friend> friends;

public List<Friend> getFriends() {
    return friends;
}

public void setFriends(List<Friend> friends) {
    this.friends = friends;
}    
}

However, I get an Jackson exception stating that "friend" is an unrecognized field. How would I have a collection of Friends and maintain the type of Friend?

Upvotes: 1

Views: 793

Answers (3)

stevevls
stevevls

Reputation: 10843

Looks to me like you have an extra property name in there. Jackson is expecting JSON like this to correspond to your Objects:

"socialConnectionsData" : {
  "friends" : [ {
      "firstname" : "John",
      "lastname" : "Doe"
    }]
}

You shouldn't need to do anything to maintain the type of Friend because your list is declared with that as a generic parameter.

If you want to go the other way around and make your objects match the JSON, then you'll need an extra level of indirection like so:

public class SocialConnectionsData {
    private List<FriendWrapper> friends;

    public List<FriendWrapper> getFriends() {
        return friends;
    }

    public void setFriends(List<FriendWrapper> friends) {
        this.friends = friends;
    }    
}

public class FriendWrapper {
    private Friend friend;

    public Friend getFriend() {
        return friend;
    }

    public void setFriend(Friend friend) {
        this.friend = friend;
    }
}

Upvotes: 1

StaxMan
StaxMan

Reputation: 116472

Your JSON must match your Object structure, and here error message does point out the problem: your main level object (SocialConnectionsData) does not have property "socialConnectionsData". Name of the class is irrelevant.

So either you should drop outermost "socialConnectionsData" or use wrapper object like:

class Wrapper {
  public SocialConnectionsData socialConnectionsData; // and/or setter to set it
}

and bind to it. This would make JSON and object structure match.

Upvotes: 1

mrk
mrk

Reputation: 5117

Because the property is "friends" not "friend"?

Upvotes: 1

Related Questions