使用 Jackson,我知道我可以通过使用 @JsonView
在 View 的序列化中包含/排除属性。
如何根据 View 改变 JSON 属性的值?
例如,我可能希望属性值在 View A 中是整个对象,在 View B 中是过滤掉某些属性的对象,在 View C 中,我只希望它是“id”(没有对象),在 View D 中,我可能希望它是“名称”(无对象):
// view A JSON
{
"prop": {"id": 123, "name": "abc", "description": "def"}
}
// view B JSON
{
"prop": {"id": 123, "name": "abc"}
}
// view C JSON
{
"prop": 123
}
// view D JSON
{
"prop": "abc"
}
最佳答案
您可能可以使用泛型来实现这一点,但您还需要提前知道要使用的具体类,例如:
public static void main(String[] args) throws Exception {
final ObjectMapper mapper = new ObjectMapper();
final MyStuff<Prop> myStuff = mapper.readValue("{\"prop\": {\"id\": 123, \"name\": \"abc\", \"description\": \"def\"}}", MyStuff.class);
final MyStuff<String> myStuff1 = mapper.readValue("{\"prop\": \"abc\"}", MyStuff.class);
final MyStuff<Integer> myStuff2 = mapper.readValue("{\"prop\": 123}", MyStuff.class);
}
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Prop {
private Integer id;
private String name;
private String description;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
public static class MyStuff<T> {
private T prop;
public T getProp() {
return prop;
}
public void setProp(T prop) {
this.prop = prop;
}
}
所以不确定这是否是您想要的。
关于java - jackson :通过 View 改变 JSON 属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29853932/