2016-02-25 40 views
1

如果我有一個JSON響應,看起來像這樣:的Java解析JSON領域進入週期

{ 
    year: 40, 
    month: 2, 
    day: 21 
} 

這代表着一個人的年齡。我有一個類來存儲:

public class User { 
    private Period age; 
} 

如何解析單個數字並創建一個Period對象?

+0

沒有人知道什麼是你的'Period'類裏,但我認爲你在找什麼是分析和提取值即JSON表示。我對麼? –

+0

@ɐuıɥɔɐɯ對不起,我應該提到,它是Java 8的時間庫中的標準Period類。基本上,我需要採取每個數字,並做類似'Period.of(年,月,日)' – Richard

+0

這可能有所幫助:http://stackoverflow.com/questions/2591098/how-to-parse-json -in-java的 – Ceelos

回答

2

如果您正在使用傑克遜,你可以寫一個簡單的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 
    } 
} 
2

你應該實現一個客戶解串器。見the Awita's answer

但是,只是爲了記錄,有an official datatype Jackson module它認識到Java 8日期&時間API數據類型。它代表Period作爲ISO-8601格式的字符串,而不是您聲明的對象。但是如果你願意改變格式,你可以考慮使用該模塊。

下面是一個例子:

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"