- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我能够序列化和反序列化抽象基类注释的类层次结构
@JsonTypeInfo(
use = JsonTypeInfo.Id.MINIMAL_CLASS,
include = JsonTypeInfo.As.PROPERTY,
property = "@class")
但没有@JsonSubTypes
列出子类,子类本身也相对没有注释,在构造函数上只有一个@JsonCreator
。 ObjectMapper 是普通的,我没有使用 mixin。
关于 PolymorphicDeserialization and "type ids" 的 jackson 文档建议(强烈)我需要抽象基类上的 @JsonSubTypes
注释,或者在 mixin 上使用它,或者我需要 register the subtypes with the ObjectMapper .并且有很多同意的问题和/或博客文章。然而它确实有效。 (这是 Jackson 2.6.0。)
所以...我是一个尚未记录的功能的受益者,还是我依赖于未记录的行为(可能会改变),还是发生了其他事情? (我问是因为我真的不希望它是后两者中的任何一个。但是 I gots to know 。)
编辑:添加代码 - 和一条评论。评论是:我应该提到我要反序列化的所有子类都与基本抽象类在同一个包和同一个 jar 中。
抽象基类:
package so;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
@JsonTypeInfo(
use = JsonTypeInfo.Id.MINIMAL_CLASS,
include = JsonTypeInfo.As.PROPERTY,
property = "@class")
public abstract class PolyBase
{
public PolyBase() { }
@Override
public abstract boolean equals(Object obj);
}
它的子类:
package so;
import org.apache.commons.lang3.builder.EqualsBuilder;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public final class SubA extends PolyBase
{
private final int a;
@JsonCreator
public SubA(@JsonProperty("a") int a) { this.a = a; }
public int getA() { return a; }
@Override
public boolean equals(Object obj) {
if (null == obj) return false;
if (this == obj) return true;
if (this.getClass() != obj.getClass()) return false;
SubA rhs = (SubA) obj;
return new EqualsBuilder().append(this.a, rhs.a).isEquals();
}
}
子类 SubB
和 SubC
是相同的,只是字段 a
被声明为 String
(不是 int
) 在 SubB
和 boolean
(不是 int
) 在 SubC
(和方法 getA
进行了相应的修改)。
测试类:
package so;
import java.io.IOException;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.testng.annotations.Test;
import static org.assertj.core.api.Assertions.*;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
public class TestPoly
{
public static class TestClass
{
public PolyBase pb1, pb2, pb3;
@JsonCreator
public TestClass(@JsonProperty("pb1") PolyBase pb1,
@JsonProperty("pb2") PolyBase pb2,
@JsonProperty("pb3") PolyBase pb3)
{
this.pb1 = pb1;
this.pb2 = pb2;
this.pb3 = pb3;
}
@Override
public boolean equals(Object obj) {
if (null == obj) return false;
if (this == obj) return true;
if (this.getClass() != obj.getClass()) return false;
TestClass rhs = (TestClass) obj;
return new EqualsBuilder().append(pb1, rhs.pb1)
.append(pb2, rhs.pb2)
.append(pb3, rhs.pb3)
.isEquals();
}
}
@Test
public void jackson_should_or_should_not_deserialize_without_JsonSubTypes() {
// Arrange
PolyBase pb1 = new SubA(5), pb2 = new SubB("foobar"), pb3 = new SubC(true);
TestClass sut = new TestClass(pb1, pb2, pb3);
ObjectMapper mapper = new ObjectMapper();
// Act
String actual1 = null;
TestClass actual2 = null;
try {
actual1 = mapper.writeValueAsString(sut);
} catch (IOException e) {
fail("didn't serialize", e);
}
try {
actual2 = mapper.readValue(actual1, TestClass.class);
} catch (IOException e) {
fail("didn't deserialize", e);
}
// Assert
assertThat(actual2).isEqualTo(sut);
}
}
此测试通过,如果您在第二行 try {
中断,您可以检查 actual1
并查看:
{"pb1":{"@class":".SubA","a":5},
"pb2":{"@class":".SubB","a":"foobar"},
"pb3":{"@class":".SubC","a":true}}
所以三个子类被正确序列化(每个子类都以它们的类名作为id)然后反序列化,结果比较相等(每个子类都有一个“值类型”equals()
)。
最佳答案
Jackson 有两种方法可以在序列化和反序列化中实现多态性。它们在link 中的第1 节。用法 中定义。你发布了。
你的代码
@JsonTypeInfo(
use = JsonTypeInfo.Id.MINIMAL_CLASS,
include = JsonTypeInfo.As.PROPERTY,
property = "@class")
是第二种方法的一个示例。首先要注意的是
All instances of annotated type and its subtypes use these settings (unless overridden by another annotation)
所以这个配置值传播到所有子类型。然后,我们需要一个类型标识符,它将 Java 类型映射到 JSON 字符串中的文本值,反之亦然。在您的示例中,这是由 JsonTypeInfo.Id#MINIMAL_CLASS
给出的
Means that Java class name with minimal path is used as the type identifier.
因此,从目标实例生成一个最小类名,并在序列化时写入 JSON 内容。或者使用最小类名来确定反序列化的目标类型。
您也可以使用 JsonTypeInfo.Id#NAME
其中
Means that logical type name is used as type information; name will then need to be separately resolved to actual concrete type (
Class
).
要提供这样的逻辑类型名称,请使用 @JsonSubTypes
Annotation used with
JsonTypeInfo
to indicate sub types of serializable polymorphic types, and to associate logical names used within JSON content (which is more portable than using physical Java class names).
这只是实现相同结果的另一种方法。您询问的有关状态的文档
Type ids that are based on Java class name are fairly straight-forward: it's just class name, possibly some simple prefix removal (for "minimal" variant). But type name is different: one has to have mapping between logical name and actual class.
因此,处理类名的各种 JsonTypeInfo.Id
值是直截了当的,因为它们可以自动生成。但是,对于类型名称,您需要明确给出映射值。
关于java - jackson 的@JsonSubTypes 是否仍然需要多态反序列化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31665620/
我目前正在对一个 mmorpg 的二进制网络协议(protocol)进行逆向工程。我正在用 java 实现该协议(protocol)。 对于每个数据包类型,我将创建一个表示二进制数据的类。 例如,聊天
我正在尝试围绕现有类编写半透明包装器,我希望它能够模仿其他类的序列化。 例如,给定以下类: class Foo { [JsonConverter(CustomConverter)] s
是否有使用 Jackson 序列化和反序列化枚举集的简单方法? private enum Type { YES, NO } @JacksonXmlProperty(localName = "t
我很想知道当我们反序列化一个对象时会发生什么。 例如,如果我的类对象由许多其他对象组成,对象创建过程如何在反序列化过程中发生 最佳答案 对象是用默认的初始化字段创建的,然后用从串行流中获取的属性值填充
我正在尝试序列化和反序列化(使用 QDataStream 但这与这里无关)一个 enum class变量: enum class Type : char { Trivial, Comp
我不确定这到底有什么问题...它不会为我编译,我将它从 c 翻译成 C++(或尝试)...是的,我是初学者。谢谢! #include #include using namespace std; i
我遇到的问题与此处描述的问题非常相似:Combining type and field serializers case class(id: Option[UUID], otherValue:Stri
我们知道base中的apply()可以对数组的边距应用一个函数,边距应该是行或列。我想将边距扩大到“对角线” 和“反对角线”。结构看起来像 diagApply <- function(x, FUN,
我找到了 JSON serialization and deserialization to objects in Flutter 的例子但是如何使用像这样的人员列表来做到这一点: [ {
我有一个相当大的terms聚合结果,这些结果被加载到下拉列表中以提供filter功能。 可以说,我的下拉列表中有4000多种动物。我的另一个下拉列表有4种动物颜色。 例, animal --> ["d
我需要将 C# (.NET Framework 4.5.2) 中的一个类与 XML 序列化(反序列化),该类具有 string 的字典属性。键和 string[]数组值。我正在使用 Serializa
[已解决]应用给定的解决方案,效果很好! 程序的目的:在用户打开和关闭程序时保存/重新加载以前的数据。 我曾经用一个对象(obj)成功(反)序列化,现在我有两个不同类的不同对象。 我试图通过查看其他帖
问题 假设我有一个代表某事或其他的枚举: public enum ResultState { Found, Deleted, NotFound } 在我的序列化 json 中,
是否有取消 JSON 字符串的功能?我猜它不会内置到 JQuery 中,但它可以通过编写一个操纵字符串的脚本来实现吗?我在下面遇到了这个问题。 我正在使用 NYTimes API,但它不支持 JSON
对于这个问题,假设当对象完全写入流并成功读出时,或者当对象部分写入流并且读回对象时发生异常时,序列化/反序列化是原子的。假设写操作可能无法成功完成,例如因为停电了。 在Serializable的描述中
有谁知道时序检查是否仍在检测虚拟环境?我尝试使用 rdtsc 指令来获取 cpu 周期并比较真实 linux 机器和在 virtualbox 上运行的 linux 之间的结果。但结果似乎不稳定。有时,
我正在对一个(外部给定的)XML 文件进行操作,该文件具有以下形式的元素 10 20 30 40 50 60 70 80 我知道如何将属性作为属性处理(通过使用 [XmlAttri
我有一个通用的序列化器和反序列化器,用于通过网络连接发送的消息: public static async Task SerializeObject(Object obj) {
我正在考虑将当前基于 WCF 的应用程序迁移到 protobuf-net.Grpc。这似乎是可行的,但是我无法在不包含所有具有 [ProtoInclude] 属性的派生类的情况下使(DTO 类)基类的
我正在尝试将一些数据保存到文件中,但文件保存到的目录不正确。 using (StreamWriter sw = new StreamWriter(dir + "\\temp" + x + ".txt"
我是一名优秀的程序员,十分优秀!