使用Jackson,我知道可以使用来为视图添加/排除属性@JsonView。
如何按视图更改JSON属性的值?
例如,我可能希望视图A中的属性值是整个对象,视图B中的属性值被滤除某些属性,在视图C中,我只希望它是“ id”(无对象),并且在视图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"
}
Run Code Online (Sandbox Code Playgroud)
您可能可以使用泛型来实现这一点,但您还需要提前知道要使用什么具体类,例如:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
所以不确定这是否是你想要的。
| 归档时间: |
|
| 查看次数: |
373 次 |
| 最近记录: |