使用Spring和Jackson JSON将java.io.Serializable实例序列化为JSON [英] Serializing java.io.Serializable instance into JSON with Spring and Jackson JSON
问题描述
我从一些内部API中获取 Serializable
的实例。 Serializable
实例实际上是 Long
或 String
等。有没有办法让DTO能够处理这种情况?使用私有可序列化值;
JSON以值结束:{}
。
I am getting an instance of Serializable
out of some internal APIs. The Serializable
instance is actually Long
or String
, etc. Is there a way to make a DTO that can handle this situation? Using private Serializable value;
the JSON ends up with value: {}
.
更新
以下是相关代码的简化示例:
Here is a reduced example of the code in question:
@Controller
public class SomeController
{
//...
public MyDto getInfo(Long id)
{
MyDto result = new MyDto();
Serializable obj = svc.getInfo(id);
// obj is either Long, or String, or one of few more fundamental Java types
result.setValue(obj);
return result;
}
}
public class MyDto
{
private Serializable value;
public void setValue(Serializable info)
{
this.value = value;
}
public Serializable getValue()
{
return value;
}
}
更新2
我在这里找到了问题的答案: https://stackoverflow.com / a / 20494813/341065
I have found the answer to my problem here: https://stackoverflow.com/a/20494813/341065
推荐答案
请注意,Jackson不使用 java.io .Serializable
任何东西:添加它没有实际价值。它会被忽略。
Note that Jackson does not use java.io.Serializable
for anything: there is no real value for adding that. It gets ignored.
鉴于此,杰克逊将看到的值等同于任何实际类型(对于序列化,即编写JSON);或者,当读取时,相当于 java.lang.Object
。
Given this, Jackson will see values as equivalent of whatever actual type is (for serialization, i.e. writing JSON); or, when reading, as equivalent of java.lang.Object
.
如果您知道实际类型,那么可以使用 @JsonDeserialize(as = ActualType.class)
注释属性以提供提示。但是如果实际值是 String
s和 Long
s,那么确实不需要这样做。
If you know the actual type, you could annotate property with @JsonDeserialize(as=ActualType.class)
to give a hint. But if actual values are String
s and Long
s, this really should not be needed.
这篇关于使用Spring和Jackson JSON将java.io.Serializable实例序列化为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!