简体   繁体   English

杰克逊反序列化到诸如property_ *的列表属性

[英]Jackson deserialize to a list properties like property_*

I need to serialize a object class: 我需要序列化一个对象类:

public class DigitalInput {

    private String id;
    private Date timestamp;
    private String matter;
    private String comment;
    private String channelId;

    private List<IndexableProperty> otherProps;
    ...
}

And I receive this JSON: 我收到此JSON:

{
    "timestamp":"2015-07-27T10:47:53.765Z",
    "matter":"aleatory-1",
    "comment":"aleatory comment-1",
    "channelId":null,
    "property_aleatoryString":"account-1@domain.com",
    "property_aleatoryNumber":6.3573580981989274E17,
    "property_aleatoryDouble":1.2,
    "property_aleatoryDate":"2015-07-27T08:03:01.9892765Z"
}

So, I need to set all property_* properties inside the otherProps list as IndexableProperty objects. 因此,我需要将otherProps列表内的所有property_ *属性设置为IndexableProperty对象。

I've created a Deserializer to do that: 我创建了一个反序列化器来做到这一点:

public class DigitalInputDeserializer extends JsonDeserializer<DigitalInput> {

     @Override
     public DigitalInput deserialize(JsonParser p, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

        JsonNode node = p.getCodec().readTree(p);
        String id = node.get("_id").asText();
        Date timestamp = Instant.parse(node.get("timestamp").asText()).toDate();
        String matter = node.get("matter").asText();
        String description = node.get("comment").asText();
        String channelId = node.get("channelId").asText();

        ...  // I don't know how to deserialize property_* like fields in a list

        return new DigitalInput(id, channelId, timestamp, matter, description);
    }

}

EDIT 编辑

I've added next, the configuration of ObjectMapper: 接下来,我添加了ObjectMapper的配置:

@ApplicationScoped
public class JacksonApplicationResources
{

    protected ObjectMapper mapper;

    @PostConstruct
    protected void initialize_resources() throws IllegalStateException
    {
        this.mapper = new ObjectMapper();

        SimpleModule module = new SimpleModule();

        // Chanel
        module.addDeserializer(Channel.class, new ChannelDeserializer());
        module.addSerializer(Channel.class, new ChannelSerializer());

        module.addDeserializer(DigitalInput.class, new DigitalInputDeserializer());
        module.addSerializer(DigitalInput.class, new DigitalInputSerializer());

        this.mapper.registerModule(module);
    }

    public ObjectMapper getMapper() {
        return this.mapper;
    }
}

The following code must be placed instead of '... // I don't know...': 必须放置以下代码,而不是“ ... //我不知道...”:

List<IndexableProperty> list = new ArrayList();

Iterator<Map.Entry<String, JsonNode>> iterator = node.fields();
while(iterator.hasNext()) {
    Map.Entry<String, JsonNode> entry = iterator.next();
    String key = entry.getKey();
    if (key.startsWith("property_")) {
        String propertyKey = StringUtils.substringAfter(key, "property_");
        IndexableProperty prop = new IndexableProperty(propertyKey, entry.getValue().asText());
        list.add(prop);
    }
}
// 'list' is initialized with props

Keep in mind a few things: 请记住以下几点:

  1. I used Apache Commons Lang for extracting substring. 我使用Apache Commons Lang提取子字符串。
  2. You should decide what to do with entry.getValue() , because exact type of JsonNode is unknown (blocks of if-instanceof can be used, but mapping name-to-type is a better approach) 您应该决定如何处理entry.getValue() ,因为JsonNode确切类型是未知的(可以使用if-instanceof块,但是将名称映射为更好的方法)

You can also consider implementing the same functionality without custom deserialization using the @JsonAnySetter annotation . 您还可以考虑使用@JsonAnySetter批注实现相同的功能,而无需自定义反序列化。

Here is a complete example: 这是一个完整的示例:

public class JacksonAnySetter {
    private static final String JSON = "{\n"
            + "    \"timestamp\":\"2015-07-27T10:47:53.765Z\",\n"
            + "    \"matter\":\"aleatory-1\",\n"
            + "    \"comment\":\"aleatory comment-1\",\n"
            + "    \"channelId\":null,\n"
            + "    \"property_aleatoryString\":\"account-1@domain.com\",\n"
            + "    \"property_aleatoryNumber\":6.3573580981989274E17,\n"
            + "    \"property_aleatoryDouble\":1.2,\n"
            + "    \"property_aleatoryDate\":\"2015-07-27T08:03:01.9892765Z\"\n"
            + "}";

    public static class IndexableProperty {
        public final String key;
        public final String value;

        public IndexableProperty(final String key, final String value) {
            this.key = key;
            this.value = value;
        }

        @Override
        public String toString() {
            return "IndexableProperty{" +
                    "key='" + key + '\'' +
                    ", value='" + value + '\'' +
                    '}';
        }
    }

    public static class DigitalInput {

        @JsonProperty
        private String id;
        @JsonProperty
        private Date timestamp;
        @JsonProperty
        private String matter;
        @JsonProperty
        private String comment;
        @JsonProperty
        private String channelId;

        private List<IndexableProperty> otherProps = new ArrayList<>();

        @JsonAnySetter
        public void setOtherProps(final String key, final String value) {
            this.otherProps.add(new IndexableProperty(key, value));
        }

        @Override
        public String toString() {
            return "DigitalInput{" +
                    "id='" + id + '\'' +
                    ", timestamp=" + timestamp +
                    ", matter='" + matter + '\'' +
                    ", comment='" + comment + '\'' +
                    ", channelId='" + channelId + '\'' +
                    ", otherProps=" + otherProps +
                    '}';
        }
    }

    public static void main(String[] args) throws IOException {
        final ObjectMapper objectMapper = new ObjectMapper();
        System.out.println(objectMapper.readValue(JSON, DigitalInput.class));
    }
}

Output: 输出:

DigitalInput{id='null', timestamp=Mon Jul 27 14:47:53 MSK 2015, matter='aleatory-1', comment='aleatory comment-1', channelId='null', otherProps=[IndexableProperty{key='property_aleatoryString', value='account-1@domain.com'}, IndexableProperty{key='property_aleatoryNumber', value='6.3573580981989274E17'}, IndexableProperty{key='property_aleatoryDouble', value='1.2'}, IndexableProperty{key='property_aleatoryDate', value='2015-07-27T08:03:01.9892765Z'}]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM