2017-10-16 54 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是这样,所以我不能改变数据结构。 –