2

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

我想通过反序列化上面的json来构造一个集合。我应该在下面的主机类中添加什么杰克逊注释


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 + '\'' +
                '}';
    }
}


有什么建议么?

注意 - 我使用的是 jackson 2.x API。

谢谢。

更新 添加包装对象就可以了。


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);



4

1 回答 1

3

请参阅这篇文章 - 这应该与您的问题相同,即使使用了不同的 API:

JsonMappingException:当前令牌不是 START_OBJECT(需要解开根名称'Transaction[]'),而是 START_ARRAY

于 2013-08-28T07:40:48.160 回答