Reputation: 65
I have a class that I want to serialize ignoring some properties
public class User extends Model
{
static class publicView{}
@JsonView(publicView.class)
private Long id;
private String showName;
@JsonView(publicView.class)
private List<qQueue> callableQueues;
}
When I serialize without JsonView I usually do something like this
public JsonNode jsonSerialization()
{
ObjectMapper mapper = new ObjectMapper();
return mapper.convertValue(this, JsonNode.class);
}
How can I serialize with the "publicView" class ?
Upvotes: 2
Views: 5208
Reputation: 65
Thanks to Alexey Gavrilov I have found a solution, It may not be the most appropriate but works.
public JsonNode jsonSerialization()
{
ObjectMapper mapper = new ObjectMapper();
try
{
mapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION);
return Json.parse(mapper.writerWithView(publicView.class).writeValueAsString(this));
}
catch (JsonProcessingException ex)
{
return null;
}
}
Upvotes: 2
Reputation: 10853
You can configure the object mapper to include your publicView.class
and exclude other fields as follows:
MapperFeature.DEFAULT_VIEW_INCLUSION
mapper feature.ObjectMapper#getSerializationConfig().withView()
method.See this page for reference.
Here is an example:
public class JacksonView1 {
public static class publicView{}
public static class User {
public User(Long id, String showName, List<String> callableQueues) {
this.id = id;
this.showName = showName;
this.callableQueues = callableQueues;
}
@JsonView(publicView.class)
public final Long id;
public final String showName;
@JsonView(publicView.class)
public final List<String> callableQueues;
}
public static void main(String[] args) {
User user = new User(123l, "name", Arrays.asList("a", "b"));
ObjectMapper mapper = new ObjectMapper();
mapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION);
mapper.setConfig(mapper.getSerializationConfig()
.withView(publicView.class));
System.out.println(mapper.convertValue(user, JsonNode.class));
}
}
Output:
{"id":123,"callableQueues":["a","b"]}
Upvotes: 9