2017-10-16 46 views
0

我想將JSON文檔中的某些鍵用作類中的值,但我不想使用Map。傑克遜JSON鍵作爲類中的值

我有與下列形式的JSON文件:

{ 
"GateWay": { 
    "API1": { 
    "Infos": "More", 
    "Meta": [1,2,3] 
    }, 
    "API2": { 
    "Infos": "Even more", 
    "Meta": [4,5,6] 
    }, 
    "API3": { 
    "Infos": "Nope", 
    "Meta": [] 
    } 
} 

我想這個結構來進行反序列化的Java類是這樣的:

class GateWays { 
    List<GateWay> gateWays; 
} 

class GateWay { 
    String name; // API1, API2 or API3 for example 

    String infos; 

    List<Integer> meta; 
} 

我如何告訴傑克遜拿作爲一個班級的價值而不是使用地圖的關鍵?

+0

我不認爲我打破JSON合約,JSON就這樣來了,我想將它導入到一個更方便的POJO結構中,而不需要額外的映射來處理我的JAVA代碼中導入的數據。 –

回答

0

嘗試如下:

class Result{ 
    GateWay GateWay; 

    //getter and setter 
} 

class GateWay { 
    Api API1; // API1, API2 or API3 for example 
    //getter and setter 
} 

class Api{ 
    String Infos; 
    List<Integer> Meta; 

    //getter and setter 
} 
+0

對不起,我的問題不夠清楚,關鍵是不固定的甚至可以像API1000等命名...... –

0

我只是考慮下面是你的POST方法...

@POST 
@Produces(MediaType.APPLICATION_JSON) 
@Consumes(MediaType.APPLICATION_JSON) 
public Response YourPostMethod(@Context UriInfo info, GateWays gateways, @HeaderParam("your_header_porom") String yourheaderporom ......); 

現在你需要聲明兩個類,如下(其中一個是內部類在這裏)

import org.codehaus.jackson.annotate.JsonIgnoreProperties; 
    import org.codehaus.jackson.map.annotate.JsonSerialize; 
    import java.io.Serializable; 

    @JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT) 
    @JsonIgnoreProperties(ignoreUnknown=true) 
    public class GateWays { 
    List<GateWay> gateWays; 

    public List<GateWay> setGateWays(){ 
    return this.gateWays; 
    } 
    public void setGateWays(ist<GateWay> gateWays){ 
     this.gateWays = gateWays; 
    } 

    @JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT) 
    public static class GateWay implements Serializable { 
    String Name; // API1, API2 or API3 for example *** Here you need to change your json message to inject APIs into it like "Name" : "API1" 
    String Infos; 
    List<Integer> Meta; 
    //add your setter and getter methods here like I did in the above class  
} 
} 

希望這會對你有幫助。

+0

JSON是這樣,所以我不能改變數據結構。 –