实例的Jackson json属性(字符串) [英] Jackson json property (string) to instance

查看:99
本文介绍了实例的Jackson json属性(字符串)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我具有以下JSON:

Assuming I have the following JSON:

{
  "property": "123:1234"
}

如何使用Jackson批注来确保将"property"的字符串值反序列化为自定义类而不是String对象? 我浏览了他们的文档,但找不到该特定功能.

How do I use Jackson annotations to ensure that the string value of "property" is de-serialized to a self-defined class rather than a String object? I went through their documentation and I was unable to find this particular feature.

谢谢.

推荐答案

您可以为您的字段创建自定义反序列化器.假设您要将其映射到SomeClass对象:

You could create custom deserializer for your field. Assuming you want to map it to SomeClass object :

public class SomeClass {

    @JsonDeserialize(using = CustomPropertyDeserializer.class)
    private Properties property;

    public Properties getProperty() {
        return property;
    }

    public void setProperty(Properties property) {
        this.property = property;
    }
}

您可以通过传递自定义反序列化器的@JsonDeserialize注释,对要自定义反序列化的字段进行注释. 您的反序列化器可能看起来像这样:

You annotate your field that you want to deserialize customly with @JsonDeserialize annotation passing custom deserializer. Your deserializer could look like this :

public class CustomPropertyDeserializer extends StdDeserializer<Properties> {

    public CustomPropertyDeserializer() {
        super(Properties.class);
    }

    @Override
    public Properties deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        String valueAsString = p.getValueAsString();
        String[] split = valueAsString.split(":");

        return new Properties(split[0], split[1]);
    }
}

和自定义属性类:

public class Properties {
    private String first;
    private String second;

    public Properties(String first, String second) {
        this.first = first;
        this.second = second;
    }

    public String getFirst() {
        return first;
    }

    public void setFirst(String first) {
        this.first = first;
    }

    public String getSecond() {
        return second;
    }

    public void setSecond(String second) {
        this.second = second;
    }
}

用于测试:

    public static void main(String[] args) throws IOException {
        String s = Files.lines(Paths.get("src/main/resources/data.json")).collect(Collectors.joining());

        ObjectMapper objectMapper = new ObjectMapper();

        SomeClass someClass = objectMapper.readValue(s, SomeClass.class);

        System.out.println(someClass.getProperty().getFirst());
        System.out.println(someClass.getProperty().getSecond());

    }

则输出为:

123
1234

因此,所有如何将String映射到您定义的类的自定义逻辑都可以放置在自定义反序列化器的deserialize方法中.

So all the custom logic how to map your String to some class that you define could be placed in deserialize method of your custom deserializer.

这篇关于实例的Jackson json属性(字符串)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆