Skip to content

Specifying a View when using jackson2 #649

@mikoet

Description

@mikoet

Hey,

I just came across this generator, and it seems to be mostly what I was needing.

But in my Java project I'm making use of com.fasterxml.jackson.annotation.View for Jackson2, that means I can generate different JSON data from the same object – depending on the context I am in.

I have looked into the docs but so far did not find if I could possibly specify a View that should be used. Any idea?

Example

My views:

public class Views {
	public static class BaseConfig {
	}

	public static class REST {
	}

	public static class Exclude {
	}
}

Sample of a persistent class that is also used in JSON communication:

package foo.bar;

import com.fasterxml.jackson.annotation.JsonView;

@Data
@Entity
public class SomeClass
{
	@Id
	@JsonView({Views.BaseConfig.class, Views.REST.class})
	private Integer id;

	@JsonView({Views.BaseConfig.class, Views.REST.class})
	private Integer parentID;
	@JoinColumn(name = "parentID", insertable = false, updatable = false)
	@ManyToOne(targetEntity = SomeClass.class, fetch = FetchType.LAZY)
	@JsonView(Views.Exclude.class) // @JsonIgnore would be an alternative for this
	private SomeClass parent;

	@Column(length = 32, nullable = false)
	@JsonView({Views.REST.class})
	private String someProperty;

	@Column(length = 32, nullable = false)
	@JsonView({Views.BaseConfig.class})
	private Long anotherProperty;
}

I then configure an ObjectMapper as follows for the JSON mapping on my REST API.

ObjectMapper mapper = new ObjectMapper();
mapper.setConfig(mapper.getSerializationConfig().withView(Views.REST.class));

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions