2016-03-21 59 views
0

使用傑克遜我該如何解析以下JSON:傑克遜解析命名對象爲同一類

{ 
    "foos" : [ 
     "one" : { 
      "prop1" : "11", 
      "prop2" : "11" 
     }, 
     "two" : { 
      "prop1" : "21", 
      "prop2" : "21" 
     }, 
     "three", 
     "four" 
    ] 
} 

這些類:

public class Root { 
    private Set<Foo> foos; 
    // ... getter and setter 
} 
public class Foo { 
    private String name; // this should contain the JSON name, e.g.: "one", "two", "three" 
    private String prop1; 
    private String prop2; 
    // ... getters and setters 
} 

關於JSON,我寧願有一個名爲對象,而比:

"foos" : [ 
    { 
     "name" : "one", 
     "prop1" : "11", 
     "prop2" : "11" 
    }, 
    { 
     "name" : "two", 
     "prop1" : "21", 
     "prop2" : "21" 
    }, 
    { 
     "name" : "three" 
    }, 
    { 
     "name" : "four" 
    } 
] 

由於大多數foos不包含其他屬性,我不知道是否第一個JSO N不太正確,但它更簡潔。

回答

1

在這種情況下,Map將適合的目的

public class Root { 
    private Set<Foo> foos; 
    // ... getter and setter 
} 

public class Foo { 
    Map<String, InternalFooProps> map = new HashMap<>();  
    class InternalFooProps{ 
     private String prop1; 
     private String prop2; 
     // ... getters and setters 
    } 
}