如何在 jackson 的注释 JSON 属性中使用正则表达式 [英] How to use regular expression in the annotation JSON property from jackson

查看:38
本文介绍了如何在 jackson 的注释 JSON 属性中使用正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jsonproperty注解可以使用正则表达式吗?是怎么做的?

Is possible use regular expression for the jsonproperty annotation and how is it done?

我有来自第三方的 json 前缀,其属性如下所示:

I have json from third party who prefix properties like below:

{ 
   "1. information": "testing"
   "2. information": "testing 2"
}

我希望所有信息都附加到列表数组信息中,请参见下面的伪示例:

I would like that all information get attach to list Array information, see below example of pseudo:

public class TimeSeries {
        @JsonProperty(/.*information/g)
        private List<String> information;
}

有时一些字符串属性也是带日期的后缀,这是可能的,但除此之外还有唯一的名称.可以在这里使用正则表达式吗?

Sometimes some of String properties is also postfix with date, is possible, but have unique name besides that. Is possible to use regular expression here?

{ 
   "Price 2019-09-01": "testing"
   "Quantity 2019-09-01": "testing 2"
}

推荐答案

我通过反序列化找到了答案,见下例:

I found the answer through deserialize, see below example:

@JsonIgnoreProperties(ignoreUnknown = true)
@Getter
@Setter
@NoArgsConstructor
public class TimeSeries {

    @JsonProperty("Meta Data")
    private MetaData metaData;

    @JsonDeserialize(using = MetaDataDeserializer.class)
    @Getter
    @Setter
    @NoArgsConstructor
    static class MetaData {
        private String information;
        private String symbol;
    }

    private static class MetaDataDeserializer extends StdDeserializer<MetaData> {
        protected MetaDataDeserializer() {
            super(MetaData.class);
        }

        @Override
        public MetaData deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException {
            MetaData metaData = new MetaData();
            while (!parser.isClosed()) {
                JsonToken jsonToken = parser.nextToken();

                if (JsonToken.FIELD_NAME.equals(jsonToken)) {
                    String fieldName = parser.getCurrentName();
                    System.out.println(fieldName);

                    //jsonToken =
                    parser.nextToken();

                    if (fieldName.toLowerCase().matches(".*information")) {
                        metaData.setInformation(parser.getValueAsString());
                    }
                }
            }

            return metaData;
        }
    }
}

这篇关于如何在 jackson 的注释 JSON 属性中使用正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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