コードが指定された URL に移動し、JSON データを読み取って出力する自動化された Java テストを作成しようとしています。アクセスしようとしている JSON は次のとおりです。
{
"status": "success",
"records": [
{
"timestamp": 1381222871868,
"deviceId": "288",
"temperature": 17
},
{
"timestamp": 1381222901868,
"deviceId": "288",
"temperature": 17
},
{
"timestamp": 1381222931868,
"deviceId": "288",
"temperature": 17
},
]}
ご覧のとおり、Timestamp、DeviceId、Temperature の 3 つの要素しかありません。
私が最終的に目指しているのは、可能であれば、2 つのタイムスタンプ値を取得し、1 つの値を別の値から取得できるようにすることです。
とにかく、私は一日中これをやろうとしてきましたが、まったく運がありません. Gson を使用するように勧められ、jar ファイルをクラスパスに含めました。
誰かが何かを知っているか、何らかの形で私を助けることができれば、Googleと私自身がこれを解決しようとして疲れ果てているので、それは大歓迎です.
完全なリストを表示するために必要なコードは次のとおりですが、完全には理解できておらず、これまでのところ、それを有利に操作することはできません。
public static void main(String[] args) throws Exception
{
String jsonString = callURL("http://localhost:8000/eem/api/v1/metrics/temperature/288");
System.out.println("\n\njsonString: " + jsonString);
// Replace this try catch block for all below subsequent examples
/*try
{
JSONArray jsonArray = new JSONArray(jsonString);
System.out.println("\n\njsonArray: " + jsonArray);
}
catch (JSONException e)
{
e.printStackTrace();
}*/
try
{
JSONArray jsonArray = new JSONArray(jsonString);
int count = jsonArray.length(); // get totalCount of all jsonObjects
for(int i=0 ; i< count; i++)
{ // iterate through jsonArray
JSONObject jsonObject = jsonArray.getJSONObject(i); // get jsonObject @ i position
System.out.println("jsonObject " + i + ": " + jsonObject);
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
public static String callURL(String myURL)
{
//System.out.println("Requested URL:" + myURL);
StringBuilder sb = new StringBuilder();
URLConnection urlConn = null;
InputStreamReader in = null;
try
{
URL url = new URL(myURL);
urlConn = url.openConnection();
if (urlConn != null)
{
urlConn.setReadTimeout(60 * 1000);
}
if (urlConn != null && urlConn.getInputStream() != null)
{
in = new InputStreamReader(urlConn.getInputStream(),
Charset.defaultCharset());
BufferedReader bufferedReader = new BufferedReader(in);
if (bufferedReader != null)
{
int cp;
while ((cp = bufferedReader.read()) != -1)
{
sb.append((char) cp);
}
bufferedReader.close();
}
}
in.close();
}
catch (Exception e)
{
throw new RuntimeException("Exception while calling URL:"+ myURL, e);
}
return sb.toString();
}
乾杯