2014-05-21 160 views
2

我想抓住重複POJO屬性或Map鍵是過去我的web服務。傑克遜檢測

因此,例如,我想如果field1出現兩次拋出錯誤或映射鍵1出現了兩次:

{ 
    "field1" : 1, 
    "field1" : 2, 
    "map" : { 
    "1" : { 
     "fieldA" : "null", 
     "fieldB" : "2" 
    }, 
    "1" : { 
     "fieldX" : "null", 
     "fieldY" : "2" 
    } 
    } 
} 

回答

4

看一看這個討論:http://jackson-users.ning.com/forum/topics/detecting-duplicate-field

下面是來自一個示例代碼從出它的地圖類:

public class JacksonDuplicates { 

    private static final String JSON = "{\n" + 
      " \"field1\" : 1,\n" + 
      " \"field1\" : 2,\n" + 
      " \"map\" : {\n" + 
      " \"1\" : {\n" + 
      "  \"fieldA\" : \"null\",\n" + 
      "  \"fieldB\" : \"2\"\n" + 
      " },\n" + 
      " \"1\" : {\n" + 
      "  \"fieldX\" : \"null\",\n" + 
      "  \"fieldY\" : \"2\"\n" + 
      " }\n" + 
      " }\n" + 
      "}"; 

    private static class SingleKeyHashMap<K, V> extends HashMap<K, V> { 
     @Override 
     public V put(K key, V value) { 
      if (containsKey(key)) { 
       throw new IllegalArgumentException("duplicate key " + key); 
      } 
      return super.put(key, value); 
     } 
    } 

    public static void main(String[] args) throws IOException { 
     SimpleModule module = new SimpleModule(); 
     module.addAbstractTypeMapping(Map.class, SingleKeyHashMap.class); 
     ObjectMapper mapper = new ObjectMapper(); 
     mapper.registerModule(module); 

     mapper.readValue(JSON, Map.class); 

    } 
} 

輸出:

Exception in thread "main" java.lang.IllegalArgumentException: duplicate key field1 
    at jackson.JacksonDuplicates$SingleKeyHashMap.put(JacksonDuplicates.java:38) 
    at com.fasterxml.jackson.databind.deser.std.MapDeserializer._readAndBindStringMap(MapDeserializer.java:434) 
    at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:312) 
    at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:26) 
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2993) 
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2098) 
    at jackson.JacksonDuplicates.main(JacksonDuplicates.java:50) 
+0

這又如何在JAX-RS applciation配置? – DarVar

+0

有多種方法來實現,取決於你的使用情況。例如[此wiki頁面](http://wiki.fasterxml.com/JacksonFAQJaxRs)描述瞭如何配置用於給定mime類型的對象映射器。 –

+0

想我找到了一個解決方案 http://jackson-users.ning.com/forum/topics/configuring-custom-modules-when-using-jaxrs-provider – DarVar

9

可以使用JsonParser.Feature.STRICT_DUPLICATE_DETECTION

ObjectMapper mapper = new ObjectMapper(); 
mapper.enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION); 
MyPOJO result = mapper.readValue(json, MyPOJO.class); 

結果:

com.fasterxml.jackson.core.JsonParseException: Duplicate field 'field1' 

How to use Jackson to validate duplicated properties?後約DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY

+2

完美解決 – mvb13

+2

這個答案應該被接受! –