[英]Serializing POJO to json with some value as String or list
Assume I have this POJO: 假设我有这个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
. 我认为有一种方法可以执行类似
@OneOf
。 Any ideas? 有任何想法吗?
Like you found out, you can indeed use type java.lang.Object
. 就像您发现的那样,您确实可以使用类型
java.lang.Object
。 Another similar approach would be to use JsonNode
, if you can pre-build response type. 如果可以预先构建响应类型,则另一
JsonNode
似的方法是使用JsonNode
。
Another way to go is to use annotations @JsonValue
and a container type; 另一种方法是使用批注
@JsonValue
和容器类型。 you could then isolate details in separate holder class like: 然后,您可以将详细信息隔离在单独的holder类中,例如:
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. 在这种情况下,
methodToBuildValue()
返回的任何methodToBuildValue()
都会被序列化,而不是Wrapper
值本身。 This gives more flexibility and bit more typing; 这提供了更大的灵活性,并增加了更多的键入内容。 you could have different accessors for
Wrapper
for your own code to use. 您可以为
Wrapper
使用不同的访问Wrapper
,以使用自己的代码。
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. 不确定最好的方法是什么,但是我实际上只是建议使用这种松散类型的JSON结构可能不是一个好主意-它不容易映射到Java或C#等静态类型的语言,而且我不确定好处是。 I am assuming however that you did not define JSON structure to use so maybe that's a moot point.
但是我假设您没有定义要使用的JSON结构,所以这可能是一个有争议的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.