1

我正在尝试编写一个自动化的 Java 测试,其中代码将转到指定的 URL,读取 JSON 数据并将其打印出来。这是我要访问的 JSON;

{
    "status": "success",
    "records": [

{
            "timestamp": 1381222871868,
            "deviceId": "288",
            "temperature": 17
        },

{
            "timestamp": 1381222901868,
            "deviceId": "288",
            "temperature": 17
        },

{
            "timestamp": 1381222931868,
            "deviceId": "288",
            "temperature": 17
        },

]}

如您所见,我只有 3 个元素,时间戳、设备 ID 和温度。

如果可能的话,我最终的目标是能够获得 2 个时间戳值并从另一个值中取走一个值。

无论如何,我整天都在尝试这样做,但没有任何运气。建议我使用 Gson,并且我已将 jar 文件包含到我的类路径中。

如果有人知道任何事情或可以以任何方式帮助我,我将不胜感激,因为我已经用尽了谷歌和我自己试图解决这个问题。

这是我必须显示完整列表的代码,但我不完全理解它,到目前为止还不能对我有利;

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();
}

干杯

4

3 回答 3

0

这是通过 Google-Gson 进行操作的方法

class MyRecord
{
private long timestamp;
private String deviceId;
private Integer temperature;
           //Getters & setters
}

public static void main(String... args){
        String myJsonString=callUrl("http://mydomain.com/x.json");
        JsonParser jp = new JsonParser();
        JsonElement ele = jp.parse(myJsonString);

        Gson gg = new Gson();
        Type type = new TypeToken<List<MyRecord>>() {
        }.getType();
        List<MyRecord> lst= gg.fromJson(ele.getAsJsonObject().get("records"), type);

       //Now the json is parsed in a List of MyRecord, do whatever you want to with it
}
于 2013-10-08T20:28:59.393 回答
0

“高级” Gson 解析答案:

package stackoverflow.questions.q19252374;

import java.util.List;

import com.google.gson.Gson;

public class Q19252374 {

    class Record {
        Long timestamp;
        String deviceId;
        Long temperature;
    }

    class Container {
        List<Record> records;
    }

    public static void main(String[] args) {
        String json = "{ \"status\": \"success\", \"records\": [{\"timestamp\": 1381222871868,\"deviceId\": \"288\",\"temperature\": 17 },{\"timestamp\": 1381222901868,\"deviceId\": \"288\",\"temperature\": 17 },{\"timestamp\": 1381222931868,\"deviceId\": \"288\",\"temperature\": 17 } ]} ";

        Gson g = new Gson();
        Container c = g.fromJson(json, Container.class);
        for (Record r : c.records)
            System.out.println(r.timestamp);

    }
}

结果当然是这样的:

1381222871868

1381222901868

1381222931868

于 2013-10-09T22:14:54.167 回答
0

我已经从文件中读取了值,但您可以从 URL 中读取,提取过程代码存在于extractJson()方法中。

 public static void main(String [] args)
{
    try
    {
        FileInputStream fis=new FileInputStream("testjson.json");
        int b=0;
        String val="";
        while((b=fis.read())!=-1)
        {
            val=val+(char)b;
        }

        extractJson(val);
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}

public static void extractJson(String json)
{
    try
    {
        JSONObject jobject=new JSONObject(json);
        System.out.println("Json object Length: "+jobject.length());
        System.out.println("Status: "+jobject.getString("status"));
        JSONArray jarray=new JSONArray(jobject.getString("records"));
        System.out.println("Json array Length: "+jarray.length());

        for(int j=0;j<jarray.length();j++)
        {
            JSONObject tempObject=jarray.getJSONObject(j);
            System.out.println("Timestamp: "+tempObject.getString("timestamp"));
            System.out.println("Device Id: "+tempObject.getString("deviceId"));
            System.out.println("Temperature: "+tempObject.getString("temperature"));
        }

    }
    catch(Exception e)
    {
        e.printStackTrace();
    }

}

您可以使用ArrayList来存储将在for loop中可用的值。根据您的问题,您需要将jsonString这个变量传递给extractJson()方法。使用org.json jar 文件来处理 json。如果您可以为gson更改此设置,那么它将对您的要求有好处。

于 2013-10-08T16:25:31.333 回答