首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Jackson JSON键作为类中的值

Jackson JSON键作为类中的值
EN

Stack Overflow用户
提问于 2017-10-16 22:51:09
回答 2查看 213关注 0票数 0

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

我得到了一个JSON文档,格式如下:

代码语言:javascript
复制
{
"GateWay": {
  "API1": {
    "Infos": "More",
    "Meta": [1,2,3]
  },
  "API2": {
    "Infos": "Even more",
    "Meta": [4,5,6]
  },
  "API3": {
    "Infos": "Nope",
    "Meta": []
  }
}

我希望将此结构反序列化为Java类,如下所示:

代码语言:javascript
复制
class GateWays {
    List<GateWay> gateWays;
}

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

    String infos;

    List<Integer> meta;
}

我如何告诉Jackson将键作为类中的值,而不是使用映射?

EN

回答 2

Stack Overflow用户

发布于 2017-10-17 00:44:52

尝试如下所示:

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2017-10-17 00:51:56

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

代码语言:javascript
复制
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response YourPostMethod(@Context UriInfo info, GateWays gateways, @HeaderParam("your_header_porom") String yourheaderporom ......);

现在您需要声明两个类,如下所示(其中一个是内部类)

代码语言:javascript
复制
   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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46773152

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档