簡體   English   中英

如何從JSON URL收集數據並顯示它

[英]How to gather data from a JSON URL and display it

我正在嘗試編寫一個自動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個Timestamp值,並從另一個值中取一個值。

無論如何,我整天都在努力做到這一點,卻一點也沒有運氣。 建議使用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();
}

干杯

我已經從文件中讀取了值,但是您可以從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循環內可用的值。 從你的問題,你需要把這個變量傳遞jsonStringextractJson()方法。 使用org.json jar文件處理json。 如果您可以為gson更改此設置,那么它將滿足您的要求。

這是通過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
}

一個“高級” 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM