Jackson: change the value of the JSON property by type

Using Jackson, I know that I can include / exclude a property from serialization for presentation using @JsonView.

How to change the value of a JSON property on a view?

for example, I might want the property value in view A to be a whole object, since B is an object with certain properties filtered out in view C, I just want it to be "id" (without an object), and in to mind D, I might want it to be a "name" (without an object):

// 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"
}
+4
source share
1 answer

, , , , :

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;
    }
}

, , .

0

Source: https://habr.com/ru/post/1584541/


All Articles