杰克逊JSON键作为Class中的值

时间:2017-10-16 14:51:09

标签: java json serialization jackson

我想将JSON文档中的一些键用作类中的值,我不想使用Map。

我有一个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;
}

如何告诉杰克逊把钥匙当作课堂上的价值取代而不是使用地图?

2 个答案:

答案 0 :(得分: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
}

答案 1 :(得分: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     
 }
}

希望这会对你有所帮助。