Java 如何从JSON URL收集数据并显示它

Java 如何从JSON URL收集数据并显示它,java,json,gson,Java,Json,Gson,我正在尝试编写一个自动化的Java测试,代码将转到指定的URL,读取JSON数据并打印出来。 这是我试图访问的JSON { "status": "success", "records": [ { "timestamp": 1381222871868, "deviceId": "288", "temperature": 17 }, { "timestamp": 138

我正在尝试编写一个自动化的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();
}
publicstaticvoidmain(字符串[]args)引发异常
{
字符串jsonString=callURL(“http://localhost:8000/eem/api/v1/metrics/temperature/288");
System.out.println(“\n\njsonString:+jsonString”);
//替换以下所有后续示例中的try-catch块
/*试一试
{  
JSONArray JSONArray=新的JSONArray(jsonString);
System.out.println(“\n\n数组:+jsonArray”);
} 
捕获(JSONException e)
{
e、 printStackTrace();
}*/
尝试
{
JSONArray JSONArray=新的JSONArray(jsonString);
int count=jsonArray.length();//获取所有JSONObject的totalCount
for(int i=0;i

Cheers

我已经从文件中读取了值,但您可以从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();
    }

}
publicstaticvoidmain(字符串[]args)
{
尝试
{
FileInputStream fis=新的FileInputStream(“testjson.json”);
int b=0;
字符串val=”“;
而((b=fis.read())!=-1)
{
val=val+(char)b;
}
提取量(val);
}
捕获(例外e)
{
e、 printStackTrace();
}
}
公共静态void-extractJson(字符串json)
{
尝试
{
JSONObject jobject=新的JSONObject(json);
System.out.println(“Json对象长度:+jobject.Length());
System.out.println(“状态:”+jobject.getString(“状态”);
JSONArray jarray=newjsonarray(jobject.getString(“记录”);
System.out.println(“Json数组长度:+jarray.Length());

对于(intj=0;j,这里是如何通过谷歌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
}
类MyRecord
{
私有长时间戳;
私有字符串设备ID;
私有整数温度;
//接球手和接球手
}
公共静态void main(字符串…参数){
字符串myJsonString=callUrl(“http://mydomain.com/x.json");
JsonParser jp=新的JsonParser();
JsonElement ele=jp.parse(myJsonString);
Gson gg=新的Gson();
Type Type=new-TypeToken(){
}.getType();
List lst=gg.fromJson(ele.getAsJsonObject().get(“记录”),类型);
//现在json被解析在MyRecord列表中,您可以使用它做任何事情
}
一个“高级”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);

    }
}
package stackoverflow.questions.q19252374;
导入java.util.List;
导入com.google.gson.gson;
公开课Q19252374{
课堂记录{
长时间戳;
字符串设备ID;
长温;
}
类容器{
列出记录;
}
公共静态void main(字符串[]args){
字符串json=“{\'status\”:\'success\”,\'records\”:[{\'timestamp\:138122871868,\'deviceId\:“288\”,“temperature\”:17},{\'timestamp\”:13812291868,\'deviceId\:“288\”,“temperature\”:17},{\'timestamp\“:1221382931868,\'deviceId\”:“288\,“temperature\”:17}”;
Gson g=新的Gson();
Container c=g.fromJson(json,Container.class);
对于(记录r:c记录)
System.out.println(r.时间戳);
}
}
当然这是结果:

138122871868

138122901868

138122931868


我怀疑你已经用尽了Google:)。请先向我们展示你的尝试以及失败的原因。哈,所有链接都已经打开了!你查看过GSON的fromJson吗?这行是System.out.println(“\n\njsonString:+jsonString”);打印任何值,如果是,请将其也粘贴。如果所有值都是常量,那么您可以只使用一个json值。是的,它会像我在问题中一样打印列表。我需要的方式是让它只打印“时间戳”值,而不打印任何内容