I want to serialize the same Category class with two mapper in different resources method.
I have written two classes that serialized Category in two different ways
CategorySerialized and CategoryTreeSerialized
public class MyJacksonJsonProvider implements ContextResolver<ObjectMapper>
{
private static final ObjectMapper MAPPER = new ObjectMapper();
static {
MAPPER.enable(SerializationFeature.INDENT_OUTPUT);
MAPPER.registerModule(new SimpleModule()
.addSerializer(Category.class, new CategorySerializer(Category.class)));
}
public MyJacksonJsonProvider() {
System.out.println("Instantiate MyJacksonJsonProvider");
}
@Override
public ObjectMapper getContext(Class<?> type) {
System.out.println("MyJacksonProvider.getContext() called with type: "+type);
return MAPPER;
}
this is the simple entity Category
@Entity
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Type(type = "objectid")
private String id;
private String name;
@ManyToOne
@JsonManagedReference
private Category parent;
@JsonBackReference
@OneToMany(mappedBy = "parent", fetch = FetchType.EAGER)
@Column(insertable = false)
private List<Category> children;
....getter and setter ....
}
this is the CategoryResource
@Path(value = "resource")
public class CategoryResource {
@Inject
CategoryService categoryService;
@Context
Providers providers;
@GET
@Produces(value = MediaType.APPLICATION_JSON+";charset="+ CharEncoding.UTF_8)
@Path("/categories")
public List getCategories(){
List<Category> categories = categoryService.findAll();
return categories;
}
@GET
@Produces(value = MediaType.APPLICATION_JSON+";charset="+ CharEncoding.UTF_8)
@Path("/categoriestree")
public List getCategoriesTree(){
List<Category> categories = categoryService.findAll();
ContextResolver<ObjectMapper> cr = providers
.getContextResolver(ObjectMapper.class, MediaType.APPLICATION_JSON_TYPE);
ObjectMapper c = cr.getContext(ObjectMapper.class);
c.registerModule(new SimpleModule()
.addSerializer(Category.class, new CategoryTreeSerializer(Category.class)));
return categories;
}
CategorySerialized extends StdSerializer is registered with the provider
MAPPER.registerModule(new SimpleModule()
.addSerializer(Category.class, new CategorySerializer(Category.class)));
CategoryTreeSerialized extends StdSerializer is registered within the resources
ContextResolver<ObjectMapper> cr = providers
.getContextResolver(ObjectMapper.class, MediaType.APPLICATION_JSON_TYPE);
ObjectMapper c = cr.getContext(ObjectMapper.class);
c.registerModule(new SimpleModule()
.addSerializer(Category.class, new CategoryTreeSerializer(Category.class)));
Unfortunately this does not work because mapper is static final.
The first resource called, register the module and then does not change
For example if I call the /categoriestree resource first, I get CategoryTreeSerialized serialization.
But if after I call the /categories resource is always serialized with the CategoryTreeSerialized class and not with CategorySerialized
(And vice versa)