SpringBoot requested page and return JSON interface data into the data objects JSON

SpringBoot, we sometimes need to interface data page will be acquired, then the JSON data into an object, there are ways I tried, can be used.

First, there is a web-many data types as JSON, for example, I use this data address and click Open

The following general structure

{"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":""}

Then we need to import the required dependencies:

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

Next is the main method, the method returns JSON data acquired is a target 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;
    }
}

After the object has been JSONObject, how to turn objects? Let's create an entity class, the same attributes and properties acquired 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
}

It is then introduced into the dependent object JSON

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

The final step is to call the

//访问获得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);

Since our object data only in the data, the data is extracted data carried, then that is the key to the code JSON.parseArray(json.toString(),BtcoinEntity.class);
so it will be JSON data into an object list, and note that the property name to be consistent, otherwise it will complain!
To and you're done here, if you need to do persistence and other treatment depends on their needs.

Guess you like

Origin blog.csdn.net/rui15111/article/details/80974172