【问题标题】:Mapping JSONArray in RestTemplate Spring在 RestTemplate Spring 中映射 JSONArray
【发布时间】:2016-02-09 13:05:27
【问题描述】:

我正在尝试使用 Spring RestTemplate 映射此 JSONArray:

[{
    "Command": "/usr/sbin/sshd -D",
    "Created": 1454501297,
    "Id": "e00ca61f134090da461a3f39d47fc0cbeda77fbbc0610439d3c16a932686b612",
    "Image": "ubuntu:latest",
    "Labels": {

    },
    "Names": [
        "/nova-c1896fbd-1309-4da2-8d77-b4fe4c02fa8e"
    ],
    "Ports": [

    ],
    "Status": "Up 2 hours"
}, {
    "Command": "/usr/sbin/sshd -D",
    "Created": 1450106126,
    "Id": "7ffc9dbdd200e2c23adec442abd656ed57306955332697cb7da979f36ebf3b22",
    "Image": "ubuntu:latest",
    "Labels": {

    },
    "Names": [
        "/nova-93b9ae40-8135-48b7-ac17-12094603b28c"
    ],
    "Ports": [

    ],
    "Status": "Up 2 hours"
}]

这里是ContainersInfo类:

@JsonIgnoreProperties(ignoreUnknown = true)
public class ContainersInfo {


    private String Id;


    private List<String> Names;

    public String getId() {
        return Id;
    }

    public void setId(String id) {
        Id = id;
    }

    public List<String> getNames() {
        return Names;
    }

    public void setNames(List<String> names) {
        Names = names;
    }
}

但是,当我想获取数据时,我得到了null

ContainersInfo[] containers = syncRestTemplate.getForObject("http://192.168.1.2:4243/containers/json?all=1", ContainersInfo[].class);

for (int i = 0; i < containers.length; i++)
            System.out.println("id:" + containers[i].getId());

结果输出如下:

id:null

id:null

有什么想法,我应该怎么做?

【问题讨论】:

  • 您确定您的标签部分是对象吗?还是应该是数组?
  • 我什至不尝试映射Labels 我只是尝试在ContainersInfo 类中获取IdNames
  • 尝试删除标签。
  • @PradipBorde 我做不到,那是我从服务器收到的 JSON。

标签: java json spring resttemplate


【解决方案1】:

您的 JSON 字段名称是帕斯卡大小写,而不是骆驼大小写(通常是这种情况)。将Jackson命名策略设置为PascalCaseStrategy,即在ContainersInfo类中添加@JsonNaming(PascalCaseStrategy.class)注解。

【讨论】:

  • 是的,我知道 chrome 扩展以格式化的方式显示 JSON 数据,改变了这一点。这不是问题。
猜你喜欢
  • 2018-04-26
  • 2014-11-13
  • 2020-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-06
  • 1970-01-01
相关资源
最近更新 更多