1. 程式人生 > >SpringBoot請求網頁介面資料返回JSON以及將JSON資料轉化為物件

SpringBoot請求網頁介面資料返回JSON以及將JSON資料轉化為物件

SpringBoot中, 我們有時需要將網頁的資料介面的資料進行獲取,然後將JSON資料轉為物件,這裡有我嘗試過的方法,能夠使用。

首先有一個網頁介面有許多資料,型別為JSON,比如我所使用的這個資料地址,點選開啟

大致結構如下

{"code":0,"data":[{"close":"596","createdDate":1406160000000,"high":"608.3","low":"596","marketFrom":0,"open":"605.9","type":3,"volume":"7.68"},{"close":"596.1","createdDate":1406246400000,"high":"603.98"
,"low":"596","marketFrom":0,"open":"596","type":3,"volume":"35.282"}]
,"detailMsg":"","msg":""}

然後我們需要先匯入所需的依賴:

<dependency>
       <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20180130</version>
</dependency>

接下來是最主要的方法,方法返回獲取到的JSON資料,是一個JSONObject物件

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class GetJson {
    public JSONObject getHttpJson(String url, int comefrom) {
        try
{ URL realUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection(); connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 建立實際的連線 connection.connect(); //請求成功 if (connection.getResponseCode() == 200) { InputStream is = connection.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); //10MB的快取 byte[] buffer = new byte[10485760]; int len = 0; while ((len = is.read(buffer)) != -1) { baos.write(buffer, 0, len); } String jsonString = baos.toString(); baos.close(); is.close(); //轉換成json資料處理 // getHttpJson函式的後面的引數1,表示返回的是json資料,2表示http介面的資料在一個()中的資料 JSONObject jsonArray = getJsonString(jsonString, comefrom); return jsonArray; } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } return null; } public JSONObject getJsonString(String str, int comefrom){ JSONObject jo = null; if(comefrom==1){ return new JSONObject(str); }else if(comefrom==2){ int indexStart = 0; //字元處理 for(int i=0;i<str.length();i++){ if(str.charAt(i)=='('){ indexStart = i; break; } } String strNew = ""; //分割字串 for(int i=indexStart+1;i<str.length()-1;i++){ strNew += str.charAt(i); } return new JSONObject(strNew); } return jo; } }

得到了JSONObject物件以後,如何轉為物件呢?我們先建立一個實體類,屬性與獲取的JSON屬性一致

public class BtcoinEntity {
    private Long id;
    //開
    private String open;
    //收
    private String close;
    //時間
    private Date createdDate;
    //高
    private String high;
    //低
    private String low;
    //量
    private String volume;
    private String marketFrom;
    private String type;
    //省略getter和setter
}

然後匯入將JSON轉為物件的依賴

<dependency>
   <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.47</version>
</dependency>

最後就是呼叫了

//訪問獲得json資料
        JSONObject dayLine = new GetJson().getHttpJson(address,1);
//        System.out.println(dayLine);
        //取得data的json資料
        JSONArray json=dayLine.getJSONArray("data");
        //將json資料轉化為物件列表
        List<BtcoinEntity> list= JSON.parseArray(json.toString(),BtcoinEntity.class);

由於我們的物件資料只在data中,所以取出data所攜帶的資料,然後就是關鍵程式碼了JSON.parseArray(json.toString(),BtcoinEntity.class);
這樣就將JSON資料轉化為物件列表了,注意屬性名要一致,否則會報錯!
到這裡就大功告成,如果還需要做持久化等處理就看自己的需求了。