如何使用JSON未命名值在Spring / Java中使用REST?

时间:2014-10-06 17:03:33

标签: java json spring rest resttemplate

我是JSON和REST的新手。我使用Spring的RestTemplate来使用JSON。通过此API调用,我能够使用此JSON响应执行此操作:http://data.fcc.gov/api/block/find?latitude=39.9936&longitude=-105.0892&showall=false&format=json

JSON响应:

    {"Block":{"FIPS":"080130608005010"},"County":
    {"FIPS":"08013","name":"Boulder"},"State":
    {"FIPS":"08","code":"CO","name":"Colorado"},"status":"OK","executionTime":"8"}

但是,当我从此请求中获取此FIPS代码并尝试使用此来通过此调用从人口普查中请求信息时:http://api.census.gov/data/2012/acs5?get=B19001_002E&for=tract:060800&in=state:08+county:013&key=

这是我得到的JSON响应:

    [["B19001_002E","state","county","tract"],
    ["225","08","013","060800"]]

正如您所看到的,所有'变量'都是未命名的并且在数组中。我不知道如何使用Spring的RestTemplate使用POJO来消费它。

这是我的Java代码(其中URL是API调用的字符串):

RestTemplate restTemplate = new RestTemplate();
CensusData cd = restTemplate.getForObject(URL, CensusData.class);
System.out.println("data: " + cd.getData());

这是我的POJO(CensusData):

@JsonIgnoreProperties(ignoreUnknown = true)
public class CensusData {

     @JsonProperty
    private List<List<String>> data;

    public String getData() {
        String str = "";
        for(List<String> list : data) {
            for(String s : list) {
                str += s;
                str += " ";
            }
        }
        return str;
    }
}

问题在于我不知道在CensusData对象中命名“data”的内容,因为这些值在JSON响应中未命名。所以我抛出了这个异常:

Exception in thread "main" org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Can not deserialize instance of template.main.CensusData out of START_ARRAY token

3 个答案:

答案 0 :(得分:1)

使用Gson https://code.google.com/p/google-gson/

String result = getResponseFromServer(String url); //restful
Gson gson = new Gson();
String[][] str = gson.fromJson(result, String[][].class);

答案 1 :(得分:0)

真正的问题是您没有扩展变量来创建映射。您需要为Census Data API: Variables.创建Less than 10,000的对象映射。B19001_002E的请求参数的进一步内省,扩展到{{3}}的定义和相应的json。其中包含以下定义。

{
    "name": "B19001_002E",
    "label": "Less than $10,000",
    "concept": "B19001.  Household Income",
    "predicateType": "int"
}

成功创建此POJO后,您可以参考响应并继续下一个挑战。

答案 2 :(得分:-1)

人口普查的响应是值数组,没有键值对象,您不能使用POJO进行映射。来自Jackson的ObjectMapper#readValue()可以帮助您更轻松地完成解析任务。请查看JacksonInFiveMinutes树模型示例部分的示例。