[英]Java parsing json fields into Period
如果我有一个看起来像这样的json响应:
{
year: 40,
month: 2,
day: 21
}
那代表某人的年龄。 我有一个课程来存储:
public class User {
private Period age;
}
如何解析单个数字并创建Period
对象?
如果您正在使用Jackson,则可以编写一个简单的JsonDeserializer
如下所示:
class UserJsonDeserializer extends JsonDeserializer<User>
{
public User deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException, JsonProcessingException
{
JsonNode node = p.getCodec().readTree(p);
int year = node.get("year").asInt();
int month = node.get("month").asInt();
int day = node.get("day").asInt();
Period period = Period.of(year, month, day);
return new User(period); // User needs corresponding constructor of course
}
}
您应该实现客户反序列化器。 请参阅Awita的答案 。
但是,仅作记录用途,有一个官方数据类型Jackson模块可以识别Java 8 Date&Time API数据类型。 它以ISO-8601格式的字符串形式表示Period
,而不是您所声明的对象。 但是,如果您愿意更改格式,则可以考虑使用该模块。
这是一个例子:
public class JacksonPeriod {
public static void main(String[] args) throws JsonProcessingException {
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
final Period period = Period.of(1, 2, 3);
final String json = objectMapper.writeValueAsString(period);
System.out.println(json);
}
}
输出:
"P1Y2M3D"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.