Deserializing JSON using Jackson 2

I have a json
[
  {
    "host": {
      "name": "anotherfullhost",
      "id": 55602819,
      "operatingsystem_id": 1073012828,
      "hostgroup_id": null
    }
  },
  {
    "host": {
      "name": "dhcp.mydomain.net",
      "id": 219245707,
      "operatingsystem_id": 1073012828,
      "hostgroup_id": null
    }
  },
  {
    "host": {
      "name": "my5name.mydomain.net",
      "id": 980190962,
      "operatingsystem_id": 1073012828,
      "hostgroup_id": null
    }
  }
]
I would like to construct a Collection by deserializing the above json. What jackson annotations should I add to the below Host class

public class Host {
    @JsonProperty("id")
    private Long id;

    @JsonProperty("name")
    private String name;

    @JsonProperty("operatingsystem_id")
    private Long operatingSystemId;

    @JsonProperty("hostgroup_id")
    private Long hostGroupId;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Long getOperatingSystemId() {
        return operatingSystemId;
    }

    public void setOperatingSystemId(Long operatingSystemId) {
        this.operatingSystemId = operatingSystemId;
    }

    public Long getHostGroupId() {
        return hostGroupId;
    }

    public void setHostGroupId(Long hostGroupId) {
        this.hostGroupId = hostGroupId;
    }

    @Override
    public String toString() {
        return "Host{" +
                "name='" + name + '\'' +
                '}';
    }
}


Any suggestions? Note - I am using jackson 2.x API. Thanks. **Update** Adding a wrapper object does the trick.

public class HostWrapper {
    @JsonProperty("host")
    private Host host;

    public Host getHost() {
        return host;
    }

    public void setHost(Host host) {
        this.host = host;
    }

    @Override
    public String toString() {
        return host.toString();
    }
}

and the below code to deserialize

        ObjectMapper mapper = new ObjectMapper();
        HostWrapper[] host = mapper.readValue(jsonString, HostWrapper[].class);




What happens when you use the code you have now?

以上就是Deserializing JSON using Jackson 2的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏