2

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?

Richard
  • 5,840
  • 36
  • 123
  • 208
  • Nobody know what's inside your `Period` class, but I think what you are looking for is to parse and extract the values from that JSON representation. Am I correct? – x80486 Feb 25 '16 at 19:14
  • @ɐuıɥɔɐɯ sorry I shouldve mentioned that, it's the standard Period class from Java 8's time library. And yeah basically, i need to take each number and do something like `Period.of(year, month, day)` – Richard Feb 25 '16 at 19:16
  • This might help: http://stackoverflow.com/questions/2591098/how-to-parse-json-in-java – Ceelos Feb 25 '16 at 19:21

2 Answers2

2

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
  }
}
Awita
  • 334
  • 2
  • 8
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"
Community
  • 1
  • 1
Alexey Gavrilov
  • 10,593
  • 2
  • 38
  • 48