使用GSON在Java中解析JSON

时间:2018-05-31 13:48:10

标签: java arrays json gson

我需要解析一个这样的数组:

[  
   [  
      1527773520000,
      "0.07608800",
      "0.07609800",
      "0.07603200",
      "0.07609300",
      "34.57200000",
      1527773579999,
      "2.62910731",
      73,
      "5.00000000",
      "0.38045959",
      "0"
   ],
   [  
      1527773580000,
      "0.07604100",
      "0.07610000",
      "0.07600700",
      "0.07603100",
      "46.01600000",
      1527773639999,
      "3.49973303",
      127,
      "17.22500000",
      "1.31058409",
      "0"
   ],
   [  
      1527773640000,
      "0.07609200",
      "0.07609800",
      "0.07601500",
      "0.07609700",
      "68.49900000",
      1527773699999,
      "5.21157734",
      102,
      "61.83300000",
      "4.70470068",
      "0"
   ],
   [  
      1527773700000,
      "0.07609700",
      "0.07609800",
      "0.07602200",
      "0.07609400",
      "60.61400000",
      1527773759999,
      "4.61160915",
      71,
      "46.85800000",
      "3.56536691",
      "0"
   ],
   [  
      1527773760000,
      "0.07605900",
      "0.07610000",
      "0.07604900",
      "0.07605000",
      "136.51000000",
      1527773819999,
      "10.38675618",
      163,
      "92.85000000",
      "7.06510307",
      "0"
   ]
]

我使用下面的代码来获取上面提到的数组,然后尝试解析它,就像你在代码中看到的那样。但它不起作用,因为我是Java新手。您能否更正我的代码或了解新代码?我该怎么做才能解析数组?

非常感谢。

import java.io.*;  
import java.net.*;
import java.util.*;
import com.google.gson.*;

public class myURLConnection
{
    public static void main(String[] args) 
    {
        try
        {
            URL url;
            url = new URL("https://api.binance.com/api/v1    /klines?symbol=ETHBTC&interval=1m&limit=5");
            URLConnection urlcon = url.openConnection();
            BufferedReader br = new BufferedReader(new InputStreamReader
                                            (urlcon.getInputStream()));
            String i;
            while ((i = br.readLine()) != null) 
            {
                System.out.println(i);
                Gson gson = new Gson();
                String[] pairString;
                pairString = gson.fromJson(i, String.class);
                double test1;
                test1 = pairString[1][4] + pairString[0][4];
                System.out.format("This is the summation: %d", test1);

            }
        } 

        catch (Exception e) 
        {
            System.out.println(e);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

试试这段代码:

BufferedReader br = new BufferedReader(new InputStreamReader
                                (urlcon.getInputStream()));
StringBuilder builder = new StringBuilder();
while ((i = br.readLine()) != null) 
{
    builder.add(i);
}
Gson gson = new Gson();
String[][] pairString;
pairString = gson.fromJson(builder.toString(), pairString.getClass());