delucasvb
delucasvb

Reputation: 5813

Spring JsonView unnest nested fields

I have something similar to these two classes:

public class User {
    @JsonView(UserView.IdOnly.class)
    int userID;

    String name;
}

public class Project {
    @JsonView(ProjectView.IdOnly.class)
    int projectID;

    @JsonView(ProjectView.Summary.class)
    // JPA annotations ommitted
    User user;
}

And the following View classes:

public class UserView extends View {}

public class ProjectView extends View {
    public interface Summary extends IdOnly {}
}

public class View {
    public interface IdOnly {}
}

My controller is as follows:

@JsonView(ProjectView.Summary.class)
@RequestMapping(value="/project/", method = RequestMethod.GET)
public List getProjects() {
    return repository.findAll();
}

The JSON output, as you can see, wraps the userID inside the User object:

[
  {
    "projectID": 1,
    "user": {
      "userID": 1
    }
  }
]

This works as expected, and I can have my clients work with it, but it doesn't seem finished... I would like to get rid of the "user" wrapper:

[
  {
    "projectID": 1,
    "userID": 1
  }
]

Is there a way to do this cleanly? Preferably by using another annotation. I don't have any custom serializers yet and I would hate to have to start using them. If this can't be done with JsonViews, is there an alternative?

I know one solution would be to add a userID field to the Project class, but the setter would need a call to the repository (to also update the user field) which would mess up my class diagram.

Upvotes: 2

Views: 2135

Answers (1)

Sabarish Senthilnathan
Sabarish Senthilnathan

Reputation: 333

Looks like there's an annotation called @JsonUnwrapped that removes the object wrapper, and all properties within it are included in the parent object.

http://fasterxml.github.io/jackson-annotations/javadoc/2.0.0/com/fasterxml/jackson/annotation/JsonUnwrapped.html

Hope this helps.

Upvotes: 2

Related Questions