1

我如何杰克逊将包装器类型序列化到字符串和从字符串中序列化?

我从他们网站的两个不同示例中合并了以下内容。但是 HostName 类型被序列化/反序列化为

{ "name" : "my.host.name.com" }

当我希望它只是字符串时

"my.host.name.com"

请注意,我有很多XName 类型,因此使用了 Immutables 包装器。所以我更喜欢一个能减少样板数量的解决方案。


@Value.Immutable @AbstractName.Wrapper
public abstract class _HostName extends AbstractName { }

...

public abstract class AbstractName {

    @JsonSerialize
    @JsonDeserialize
    @Value.Style(
        // Detect names starting with underscore
        typeAbstract = "_*",
        // Generate without any suffix, just raw detected name
        typeImmutable = "*",
        // Make generated public, leave underscored as package private
        visibility = Value.Style.ImplementationVisibility.PUBLIC,
        // Seems unnecessary to have builder or superfluous copy method
        defaults = @Value.Immutable(builder = false, copy = false))
    public @interface Wrapper {}




    @Value.Parameter
    public abstract String name();

    @Override
    public String toString() { return name(); }
}
4

1 回答 1

2

我有这个像下面这样工作。我的姓名类型有一个额外的注释。这不是我最喜欢的,但它有效。

@JsonDeserialize(as=HostName.class)
@Value.Immutable @AbstractName.Wrapper
public abstract class _HostName extends AbstractName { }

...

public abstract class AbstractName {

    @Value.Style(
        // Detect names starting with underscore
        typeAbstract = "_*",
        // Generate without any suffix, just raw detected name
        typeImmutable = "*",
        // Make generated public, leave underscored as package private
        visibility = Value.Style.ImplementationVisibility.PUBLIC,
        // Seems unnecessary to have builder or superfluous copy method
        defaults = @Value.Immutable(builder = false, copy = false))
    public @interface Wrapper {}


    @JsonValue
    @Value.Parameter
    public abstract String name();

    @Override
    public String toString() { return name(); }
}

这是一个运行它的小程序:

public static void main(String... args) throws IOException {
    ObjectMapper json = new ObjectMapper();

    String text = json.writeValueAsString(HostName.of("my.host.name.com"));

    System.out.println(text);

    HostName hostName = json.readValue(text, HostName.class);
    System.out.println(hostName);
}
于 2018-02-09T05:53:26.393 回答