如果我有一个如下所示的 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
}
}
关于Java将json字段解析为Period,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35636109/