gpt4 book ai didi

java - 使用 Jackson 的不可变类反序列化 JSON 平面对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:21:35 25 4
gpt4 key购买 nike

我是 Jackson 库(1.9 版)的新手。我才使用它几个星期,我发现在 Java 中序列化和反序列化对象时,它非常灵活且节省时间。

不过,我在将“平面”JSON 反序列化为一个由另一个类组成的类时遇到了麻烦,而这两个类都应该是不可变的。

我的情况大致如下:

class Foo {

private final String var1;

Foo(String var1) {
this.var1 = var1;
}
// getters omitted
}

class A {
private final Foo foo;
private final String var2;

A(/* @JsonUnwrapped doesn't work here */ Foo foo, String var2) {
this.foo = foo;
this.var2 = var2;
}

@JsonUnwrapped
Foo getFoo() {
return foo;
}

String getVar2() {
return var2;
}
}

class B extends Foo {
private final String var2;

B(String var1, String var2) {
super(var1);
this.var2 = var2;
}
// getters omitted
}

要反序列化的 JSON 是这样的:

{ "var1" : "some_value", "var2" : "some_other_value" }

问题是:是否有一种基于注释的方式(因此,无需使用自定义反序列化器)告诉 Jackson 将给定的 JSON 组合成“A”实例?我已经尝试在类“A”构造函数中为 Foo 参数使用 @JsonUnwrapped 属性,但它在多参数构造函数中不受支持,因为它需要 JsonProperty 才能工作(这没有意义,因为实际上没有这些项目的单一属性)。相反,序列化可以使用这种模式完美地工作。

它也可以通过使用单独的 setter 来处理非不可变类,但我想知道是否有一种方法可以通过仅使用构造函数(或构建器,这在现实中有意义)来做同样的事情字段比示例中的字段多得多)。

同样的方法显然适用于继承自“Foo”的类“B”。

提前致谢。

最佳答案

请注意,Jackson 的反序列化处理不一定尊重 final 字段的不变性。因此,一种简单的方法是只提供无参数(私有(private))构造函数供 Jackson 使用。

import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonFoo
{
public static void main(String[] args) throws Exception
{
// {"var1":"some_value", "var2":"some_other_value"}
String jsonInput = "{\"var1\":\"some_value\", \"var2\":\"some_other_value\"}";

ObjectMapper mapper = new ObjectMapper().setVisibility(PropertyAccessor.FIELD, Visibility.ANY);

A a = new A(new Foo("some_value"), "some_other_value");
System.out.println(mapper.writeValueAsString(a));
// output: {"var1":"some_value","var2":"some_other_value"}

A aCopy = mapper.readValue(jsonInput, A.class);
System.out.println(mapper.writeValueAsString(aCopy));
// output: {"var1":"some_value","var2":"some_other_value"}
}
}

class Foo
{
private final String var1;

Foo(String var1) {this.var1 = var1;}

private Foo() {this.var1 = null;}
}

class A
{
@JsonUnwrapped
private final Foo foo;
private final String var2;

A(Foo foo, String var2)
{
this.foo = foo;
this.var2 = var2;
}

private A()
{
this.foo = null;
this.var2 = null;
}
}

如果您真的不想提供这样的(额外的)构造函数,那么如果可以使用 @JsonCreator 设计出类似的解决方案就好了。 ,但我无法让这样的东西工作。因此,我建议在 https://github.com/FasterXML/jackson-core/issues 记录增强请求,也许是为了更好地支持使用 @JsonUnwrapped@JsonProperty 注释 @JsonCreator 参数。

关于java - 使用 Jackson 的不可变类反序列化 JSON 平面对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11620130/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com