Java parsing json fields into Period

▼魔方 西西 提交于 2019-12-12 20:42:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!