不可变的包裹在杰克逊的字符串

时间:2018-02-09 01:01:11

标签: jackson immutables-library

我怎样才能将包装类型与字符串序列化?

我从他们的网站的两个不同的例子中合并了以下内容。但是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(); }
}

1 个答案:

答案 0 :(得分: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);
}