【发布时间】:2017-07-23 10:17:08
【问题描述】:
我想用两个映射器在不同的资源方法中序列化同一个 Category 类。
我编写了两个以两种不同方式序列化 Category 的类
CategorySerialized 和 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;
}
这是简单的实体类别
@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 ....
}
这是 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 扩展 StdSerializer 已向提供程序注册
MAPPER.registerModule(new SimpleModule()
.addSerializer(Category.class, new CategorySerializer(Category.class)));
CategoryTreeSerialized扩展StdSerializer在资源内注册
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)));
不幸的是,这不起作用,因为映射器是静态最终的。
调用的第一个资源,注册模块然后不改变
例如,如果我首先调用 /categoriestree 资源,我会得到 CategoryTreeSerialized 序列化。
但是,如果在我调用 /categories 资源后总是使用 CategoryTreeSerialized 类而不是 CategorySerialized 进行序列化
(反之亦然)
【问题讨论】:
-
有道理。你有什么问题?
-
我希望当我调用 getCategories (/categories) 时我会使用 CategorySerialized 进行序列化,而当我调用 getCategoryTree (/ categoriestree) 我使用 CategoryTreeSerialized 进行序列化
-
所以使用不同的映射器。
-
怎么样?在同一个提供商中?
-
但是,无论在哪里。我看不出有什么问题。
标签: java json serialization jackson jackson-modules