无法使用Jackson将JSON HTTP响应转换为Java对象

时间:2015-11-19 12:08:15

标签: java json jackson gson appdynamics

我创建了一个REST服务,它发送GET请求以从指定的URL检索JSON响应。

虽然我的下一个问题是将JSON消息转换为JAVA对象,但我已经将它工作到了成功检索JSON消息的程度。

以下是我的Rest客户:

public class RestADClient {


// HTTP GET request
public String sendGet(String url) throws Exception {

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    // optional default is GET
    con.setRequestMethod("GET");

    //add request header

    con.setRequestProperty("Authorization", "myAuthorizationProp");

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'GET' request to URL : " + url);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    System.out.println("Response Message: " + response.toString());

    ObjectMapper mapper = new ObjectMapper();

    try {
        // Convert JSON string to Object
        String jsonInString = "[{  \"frequency\": \"ONE_MIN\",  \"metricId\": 2253538,  \"metricName\": \"DB|Server:1|IO|Data File Average Read Size\",  \"metricPath\": \"Databases|X|IO|Data File Average Read Size\",  \"metricValues\": [  {    \"count\": 14,    \"current\": 65323,    \"max\": 65536,    \"min\": 0,    \"occurrences\": 0,    \"standardDeviation\": 0,    \"startTimeInMillis\": 1447927800000,    \"sum\": 251408,    \"useRange\": true,    \"value\": 17958  }]}]";
        ADMetrics adMetrics = mapper.readValue(jsonInString, ADMetrics.class);
        System.out.println(adMetrics);

    } catch (JsonGenerationException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return response.toString();
}

}

以下是我的ADMetrics POJO课程:

import java.util.List;
public class ADMetrics {

private String frequency;
private int metricId;
private String metricName;
private String metricPath;
private List<String> metricValues;
private int count;
private int current;
private int max;
private int min;
private int occurences;
private int standardDeviation;
private int startTimeInMillis;
private int sum;
private boolean useRange;
private int value;

public String getFrequency() {
    return frequency;
}

public void setFrequency(String frequency) {
    this.frequency = frequency;
}

public int getMetricId() {
    return metricId;
}

public void setMetricId(int metricId) {
    this.metricId = metricId;
}
public String getMetricName() {
    return metricName;
}

public void setMetricName(String metricName) {
    this.metricName = metricName;
}

public String getMetricPath() {
    return metricPath;
}

public void setMetricPath(String metricPath) {
    this.metricPath = metricPath;
}

public List<String> getMetricValues() {
    return metricValues;
}

public void setMetricValues(List<String> metricValues) {
    this.metricValues = metricValues;
}

public int getCount() {
    return count;
}

public void setCount(int count) {
    this.count = count;
}

public int getCurrent() {
    return current;
}

public void setCurrent(int current) {
    this.current = current;
}

public int getMax() {
    return max;
}

public void setMax(int max) {
    this.max = max;
}

public int getMin() {
    return min;
}

public void setMin(int min) {
    this.min = min;
}

public int getOccurences() {
    return occurences;
}

public void setOccurences(int occurences) {
    this.occurences = occurences;
}

public int getStandardDeviation() {
    return standardDeviation;
}

public void setStandardDeviation(int standardDeviation) {
    this.standardDeviation = standardDeviation;
}

public int getStartTimeInMillis() {
    return startTimeInMillis;
}

public void setStartTimeInMillis(int startTimeInMillis) {
    this.startTimeInMillis = startTimeInMillis;
}

public int getSum() {
    return sum;
}

public void setSum(int sum) {
    this.sum = sum;
}

public boolean isUseRange() {
    return useRange;
}

public void setUseRange(boolean useRange) {
    this.useRange = useRange;
}

public int getValue() {
    return value;
}

public void setValue(int value) {
    this.value = value;
}

以下是我的JUnit测试:

public class ADTest {

String url = "myURL";

@Test
public void testResponseContainsMetricFrequency() throws Exception {

    RestADClient restADClient = new RestADClient();


    assertTrue(restADClient.sendGet(url).contains("frequency"));
}}

当我运行测试时,我得到以下内容:

回复代码:200

回复消息:[{&#34;频率&#34;:&#34; ONE_MIN&#34;,&#34; metricId&#34;:2253538,&#34; metricName&#34;:&#34; DB |服务器:169 | IO |数据文件平均读取大小&#34;,&#34; metricPath&#34;:&#34;数据库| QA-CARS | IO |数据文件平均读取大小&#34;,&#34 ; metricValues&#34;:[{&#34; count&#34;:13,&#34; current&#34;:66013,&#34; max&#34;:72003,&#34; min&#34;: 0,&#34;出现&#34;:0,&#34; standardDeviation&#34;:0,&#34; startTimeInMillis&#34;:1447929360000,&#34; sum&#34;:198688,&#34; useRange&#34;:true,&#34; value&#34;:15284}]}]

org.codehaus.jackson.map.JsonMappingException:无法从START_ARRAY令牌中反序列化rest.client.ADMetrics的实例  在[来源:java.io.StringReader@78b729e6; line:1,column:1]

4 个答案:

答案 0 :(得分:0)

"[{  \"frequency\": \"ONE_MIN\",  \"metricId\": 2253538,  \"metricName\": \"DB|Server:1|IO|Data File Average Read Size\",  \"metricPath\": \"Databases|X|IO|Data File Average Read Size\",  \"metricValues\": [  {    \"count\": 14,    \"current\": 65323,    \"max\": 65536,    \"min\": 0,    \"occurrences\": 0,    \"standardDeviation\": 0,    \"startTimeInMillis\": 1447927800000,    \"sum\": 251408,    \"useRange\": true,    \"value\": 17958  }]}]"

JSON对象的形式不正确。

试试这个:

"{  \"frequency\": \"ONE_MIN\",  \"metricId\": 2253538,  \"metricName\": \"DB|Server:1|IO|Data File Average Read Size\",  \"metricPath\": \"Databases|X|IO|Data File Average Read Size\",  \"metricValues\": [  {    \"count\": 14,    \"current\": 65323,    \"max\": 65536,    \"min\": 0,    \"occurrences\": 0,    \"standardDeviation\": 0,    \"startTimeInMillis\": 1447927800000,    \"sum\": 251408,    \"useRange\": true,    \"value\": 17958  }]}"

答案 1 :(得分:0)

删除外部&#34; []&#34;来自你的JSON。您传递的是ADMetrics数组,而不是readValue反序列化程序所期望的单个ADMetrics

答案 2 :(得分:0)

您可以尝试在pojo类中实现序列化,如下所示

     public class ADMetrics implements Serializable{

private static final long serialVersionUID = 1L;
//All your variables and getter and setter method
}

方法一:

此外,您的JSON不是JSONObject它是JSONARRAY,使用下面的代码将您的上述String转换为JSONARRAY

JsonArray jArray = new JsonParser().parse(json).getAsJsonArray();

jArray是GSON的JSONArray,因此与GSON合作转换你需要的方式或将GSON转换为JSON。

OR

方法二:

直接从

转换上面的输入json
Gson gson = new Gson();
            String output = gson.toJson(input);
            //System.out.println("output from gson "+output);
        JSONArray js = new JSONArray(output);

然后像往常一样使用json。

答案 3 :(得分:0)

由于您接收的JSON具有数组,因此您需要反序列化为对象列表。大概只是抓住列表中的第一个:

    List<ADMetrics> adMetricsList = mapper.readValue(jsonInString, new TypeReference<List<ADMetrics>>(){});
    ADMetrics adMetrics = adMetricsList.get(0);

或者,如果您不确定列表中还有其他内容,并且只想获取第一个元素,则可以分两步执行转换:

    JsonNode tree = mapper.readTree(jsonInString);
    ADMetrics adMetrics = mapper.convertValue(tree.get(0), ADMetrics.class);