java - Java 将一个 JSON 字段解析为两个 Java 字段而无需设置器
问题描述
我正在使用 sprintboot,我有一个模型,例如:
public class Source {
# I have 10 annotation here validator
# @NotNull @Deserializer and other
public String raw_data;
# I have 10 annotation here validator
# @NotNull @Deserializer and other
public String fix_data;
# i have more than 100+ other field
}
我想将这些数据解析成固定版本,但仍保留原始原始版本。
{"data":"somedata"}
数据不能以数字开头。
"abc"
将是有效的"1abc"
将是无效的
所以我希望我的java类被解析为:
public class Source {
public String raw_data = "1abc";
public String fix_data = "abc";
}
我尝试使用@JsonAlias
但没有用。我也尝试使用@JsonProperty
,但我得到了error: Multiple fields representing property
.
如何将 json 值解码为两个字段?
解决方案
您可以使用 @JsonCreator 应用于构造函数来反序列化提到的 JSON 结构。
public class Source {
public String rawData;
public String fixdata;
@JsonCreator
public Source(@JsonProperty("data") String data) {
this.rawData = data;
this.fixData = data.replaceAll("^(\\d+)", ""); // removing digits at the start
}
}
测试
String json = "{\"data\":\"1abc\"}";
ObjectMapper mapper = new ObjectMapper();
Source src = mapper.readValue(json, Source.class);
System.out.printf("raw: '%s', input: '%s'%n", src.rawData, src.fixData);
输出:
raw: '1abc', input: 'abc'
推荐阅读
- r - 匹配从另一个数据框中选择最大值
- mysql - 可以将 mysql 查询扩展为另一个查询的子查询吗?
- android - 如何在android auto上的小部件上添加叠加层
- java - 如何在 Swagger 2 中为每个端点放置不同的示例?
- sql - 如何在 AWS Athena (Presto) 中使用 LIMIT OFFSET?
- hibernate - 查询存储在单独集合中的 @Embeddable 对象
- firebase - 身份验证触发的云功能(创建用户)不执行
- java - 使用 Spring Boot 和 Wicket AuthenticatedWebApplication 过滤注册
- laravel - laravel Horizon - 调试作业未运行/处理
- android - Android 检查安装源包名称