2017-02-24 103 views
2

我在使用Jackson的反序列化中遇到了一個問題,在我的休息放心的測試中使用了Jackson。 在我的JSON中,我有一個鍵「值」,可以是一個字符串或對象布爾的數組。Jackson反序列化雙重

{ 
"value": ["value1", "value2"] 
} 

{ 
"value": 2272204.2426 
} 

所以我寫了定製解串器這一領域:

public Object deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { 
     ObjectCodec oc = jp.getCodec(); 
     JsonNode node = oc.readTree(jp); 
     if (node.isArray()) { 
      List<String> list = new ArrayList<>(); 
      for (JsonNode elementNode : node) { 
       list.add(oc.treeToValue(elementNode, String.class)); 
      } 
      return list; 
     } else { 
      if(node.isDouble()) { 
       return oc.treeToValue(node, Double.class); 
      } 
      else if(node.isBoolean()){ 
       return oc.treeToValue(node, Boolean.class); 
      } 
      else { 
       return oc.treeToValue(node, String.class); 
      } 
     } 
    } 

最後,我已經注意到,像2272204.2426數值進行反序列化到2272204.2 我試着使用Gson進行解序列化,並且效果很好。你有什麼想法爲什麼使用傑克遜缺乏小數部分? 我試過調試代碼,我注意到在這一步JsonNode node = oc.readTree(jp);值爲2272204.2

回答

1

爲什麼不使用傑克遜的ObjectMapper?與ObjectCodec不同,您可以添加DeserializationFeature。 Mapper實際上擴展了Codec,但在這種情況下還需要更多功能。

ObjectMapper mapper = new ObjectMapper(); 
mapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS); 

JsonNode node = //node where the value is defined as Double 

Double value = null; 
try { 
    value = mapper.treeToValue(node, Double.class); 
} 
catch (IOException e) { 
    e.printStackTrace(); 
} 

System.out.println(value); 

使用上述邏輯在node.isDouble()情況

+1

我提到這個值字段可以是數組或對象,這就是爲什麼我使用的自定義串並轉換器和我使用這種結構 @JsonDeserialize(使用= ValueDeserializer.class) private Object value; 值只是我的目標對象中的衆多領域之一。 – baadnews

+0

謝謝你的回答。它工作正常。我注意到在不同的情況下,當我使用JsonPath從特定節點檢索對象時,會丟失小數部分。據休息,保證項目的問題清單,JsonPath(串)將全面十進制值。 – baadnews