[英]How to get data from a URL and convert it into json?
我正在嘗試從URL獲取數據,並使用以下代碼將其存儲為json格式:
String fullURL="http://XXX:8101/Myapp/XXX/XXX";
URL u = new URL(fullURL);
System.out.println(fullURL);
HttpURLConnection huc = (HttpURLConnection) u.openConnection();
System.out.println("Message :"+huc.getResponseMessage());
JSONParser parser = new JSONParser();
BufferedReader rd = new BufferedReader(new InputStreamReader(huc.getInputStream()));
JSONArray a = (JSONArray) parser.parse(rd);
for (Object o : a)
{
org.json.simple.JSONObject device = (org.json.simple.JSONObject) o;
double kw = (double) device.get("value");
System.out.println(kw);
//getKw().setKw(kw);
String sensortype = (String) device.get("senorType ");
System.out.println(sensortype);
//getSensorType().setSenorType(sensortype);
Timestamp dateTime = (Timestamp) device.get("serverTimeStamp");
System.out.println(dateTime);
//getServerTimeStamp().setServerTimeStamp(dateTime);
}
但是我收到以下錯誤:
java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray.
我在做什么錯以及如何解決這個問題?
我根據用戶評論更改了,最后我的數組是:
[
{
"value": 777,
"percentage": 0,
"serverTimeStamp": 1436900289000,
"sensorType": "S"
},
{
"value": 777,
"percentage": 0,
"serverTimeStamp": 1436900289000,
"sensorType": "V"
},
{
"value": 777,
"percentage": 0,
"serverTimeStamp": 1436900289000,
"sensorType": "R"
}
]
我怎么會收到java.lang.ClassCastException:無法將java.lang.Long強制轉換為java.lang.Double異常?
device.get("value")
返回的Long
值不能為Double
大小寫。
因此,將其更改為:
long kw = (long) device.get("value");
看你的代碼后,你想在施放價值double
這是wrong
,你會得到long
的instate double
試圖獲得的鍵值時"value"
從JSONObject
。為了得到你的願望的結果首先轉換為long
,然后在double
。
double kw = (double)((long) device.get("value"));
我觀察到的另一件事是您正在嘗試將鍵"serverTimeStamp"
值"serverTimeStamp"
為Timestamp
,這是wrong
,因為您將"serverTimeStamp"
long
來創建新的Timestamp實例。
Timestamp dateTime = new Timestamp ((long) device.get("serverTimeStamp"));
為什么不這樣做呢。
((Number) device.get("value")).doubleValue();
如果返回的實例是int,long,float,double等數字,則永遠不會獲得Class強制轉換異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.