杰克逊反序列化为列表属性,如属性_ *

时间:2015-07-27 08:28:36

标签: java json jackson

我需要序列化一个对象类:

public class DigitalInput {

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

    private List<IndexableProperty> otherProps;
    ...
}

我收到了这个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"
}

因此,我需要将otherProps列表中的所有property_ *属性设置为IndexableProperty个对象。

我已经创建了一个Deserializer来做到这一点:

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);
    }

}

修改

我接下来添加了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;
    }
}

2 个答案:

答案 0 :(得分:0)

必须放置以下代码而不是&#39; ... //我不知道......&#39;:

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

请记住以下几点:

  1. 我使用Apache Commons Lang来提取子字符串。
  2. 您应该决定如何处理entry.getValue(),因为JsonNode的确切类型未知(可以使用if-instanceof的块,但是映射名称到类型是更好的方法)

答案 1 :(得分:0)

您还可以考虑使用the @JsonAnySetter annotation实现相同的功能而无需自定义反序列化。

这是一个完整的例子:

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));
    }
}

输出:

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'}]}