1

指定した URL から JSON 応答を取得するために GET 要求を送信する REST サービスを作成しました。

次の問題はJSONメッセージをJAVAオブジェクトに変換することですが、JSONメッセージを正常に取得できるようになりました。

以下は私の残りのクライアントです:

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

応答メッセージ: [{ "frequency": "ONE_MIN", "metricId": 2253538, "metricName": "DB|Server:169|IO|Data File Average Read Size", "metricPath": "Databases|QA-CARS| IO|データ ファイルの平均読み取りサイズ", "metricValues": [ { "count": 13, "current": 66013, "max": 72003, "min": 0, "occurrences": 0, "standardDeviation": 0 、「startTimeInMillis」: 1447929360000、「合計」: 198688、「useRange」: true、「値」: 15284 }]}]

org.codehaus.jackson.map.JsonMappingException: [Source: java.io.StringReader@78b729e6;] で START_ARRAY トークンから rest.client.ADMetrics のインスタンスを逆シリアル化できません。行: 1、列: 1]

4

4 に答える 4

0

受信している JSON には配列があるため、オブジェクトのリストに逆シリアル化する必要があります。おそらく、リストの最初のものを取得するだけです:

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

または、リストに他に何があるか分からず、最初の要素だけを取得したい場合は、次の 2 つの手順で変換を行うことができます。

    JsonNode tree = mapper.readTree(jsonInString);
    ADMetrics adMetrics = mapper.convertValue(tree.get(0), ADMetrics.class);
于 2015-11-20T00:14:19.557 に答える
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  }]}"
于 2015-11-19T12:16:25.283 に答える
0

JSON から外側の「[]」を削除します。readValue デシリアライザーが期待する単一の ADMetrics ではなく、ADMetrics の配列を渡しています。

于 2015-11-19T12:17:07.693 に答える
0

以下のように、pojo クラスにシリアル化を実装してみてください。

     public class ADMetrics implements Serializable{

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

方法 1:

また、JSON は JSONObject ではなく、JSONARRAY です。以下のコードを使用して、上記の文字列を JSONARRAY に変換します。

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

jArray は GSON の JSONArray であるため、GSON を使用して必要な方法を変換したり、GSON を JSON に変換したりします。

また

方法 2:

上記の入力jsonを直接変換します

Gson gson = new Gson();
            String output = gson.toJson(input);
            //System.out.println("output from gson "+output);
        JSONArray js = new JSONArray(output);

次に、通常どおり json を操作します。

于 2015-11-19T12:17:09.907 に答える