问题
If I have a json response that looks like this:
{
year: 40,
month: 2,
day: 21
}
That represents someone's age. And I have a class to store that:
public class User {
private Period age;
}
How do I parse the individual numbers and create a Period
object?
回答1:
If you are using Jackson you can write a simple JsonDeserializer
like this:
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
}
}
回答2:
You should implement a customer deserializer. See the Awita's answer.
However, just for the record, there is an official datatype Jackson module which recognizes Java 8 Date & Time API data types. It represents Period
as a string in the ISO-8601 format, not as object your stated. But if you are willing to change the format, you can consider using that module.
Here is an example:
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);
}
}
Output:
"P1Y2M3D"
来源:https://stackoverflow.com/questions/35636109/java-parsing-json-fields-into-period