如何从URL获取数据并将其转换为json?

时间:2015-11-20 06:49:24

标签: java 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 异常?

3 个答案:

答案 0 :(得分:1)

device.get("value")返回的Long值不属于Double

所以改成它:

long kw = (long) device.get("value");

答案 1 :(得分:1)

在查看您的代码后,您试图在double wrong中投放价值,当您尝试获取long时,您将获得double "value"来自JSONObject的关键long。要将您的愿望结果首先投放到double,然后投放到double kw = (double)((long) device.get("value"));

"serverTimeStamp"

我观察到的另一件事是你试图将关键Timestamp的值转换为wrong long,这样你就可以获得Timestamp dateTime = new Timestamp ((long) device.get("serverTimeStamp")); 创建新的时间戳实例。

Sub CapsChange()
    Dim letr As String
    Dim Val1 As String

    Dim sr As Range
    lastrow = ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row

    Set sr = Range("A1:A" & lastrow)

    For Each r In sr
        Fval = r.Value
        Val1 = Left(r.Value, 1)

        If Val1 <> UCase(Val1) Then

            For i = 1 To Len(Fval)
                letr = Mid(Fval, i, 1)
                If letr = UCase(letr) Then
                    Mid(Fval,i,1) = LCase(letr)
                else
                    Mid(Fval,i,1) = UCase(letr)
                End If
            Next i

        End If

    Next

End Sub

答案 2 :(得分:0)

为什么不这样做。

 ((Number) device.get("value")).doubleValue();

如果返回的instace是int,long,float,double等数字,你永远不会得到类别转换异常。