rand0m86
rand0m86

Reputation: 3322

Serializing POJO to json with some value as String or list

Assume I have this POJO:

@JsonInclude(Include.NON_NULL)
public class Model {

    @JsonProperty(value="data")
    private String dataStr;
    private List<String> data;
}

And it should be serialized to

{ "data": "hello" }

or

{
    "data": [
        "hello",
        "world"
    ]
}

depending on some conditions. How can I do this with Jackson ?

The class given above doesn't work. The only one solution I've found so far is

@JsonInclude(Include.NON_NULL)
public class Model {

    @JsonProperty
    private Object data;
}

but it's not the best one. I think there is a way to do something like @OneOf. Any ideas?

Upvotes: 0

Views: 1105

Answers (1)

StaxMan
StaxMan

Reputation: 116522

Like you found out, you can indeed use type java.lang.Object. Another similar approach would be to use JsonNode, if you can pre-build response type.

Another way to go is to use annotations @JsonValue and a container type; you could then isolate details in separate holder class like:

public class Model {
    public Wrapper data;
}

public class Wrapper {
    @JsonValue
    public Object methodToBuildValue() {
       // code to figure out what to return, String, List etc
    }
}

and in this case whatever methodToBuildValue() returns is serialized instead of Wrapper value itself. This gives more flexibility and bit more typing; you could have different accessors for Wrapper for your own code to use.

Not sure what the best way is, but I would actually just suggest that use of such loosely typed JSON structures is probably not a good idea -- it is not easily mappable to statically typed languages like Java or C#, and I am not sure what the benefit is. I am assuming however that you did not define JSON structure to use so maybe that's a moot point.

Upvotes: 2

Related Questions