java - jackson :通过 View 改变 JSON 属性值

标签 java json jackson

使用 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/

相关文章:

Java 并发实践 list 6.2

javascript - Node js,process.env 不读取环境变量

java - 在 Android 上使用 Jackson 库解析大型 JSON 时出现内存不足错误

Java Spring : Web Service REST producing double backslash at JSON

android - 使用 Volley 发布 JsonObject

java - 为什么ObjectNode在Json字符串中添加反斜杠

java - 无法从 START_OBJECT token 中反序列化 java.lang.Class 的实例

java - 如何以编程方式将 EditText 背景设置为 Holo 主题 Api 11-17 Android 中的默认背景

java - 我需要使用 Apache POI 在 Excel 工作表上的 Java 中迭代到列的末尾

java - 使用列表的一部分进行比较时的自定义 hashCode