java解析從接口獲取的json內容並寫到excle(只寫與標題匹配的值,並非把所有的接口返回值都寫進去)


需求:從接口中獲取的一個json數組中有多個對象,每個對象中的值並非都需要,只需查出標題中的幾項對應的值即可。且還需要按某個字段排序后依次寫到excel

實現方法如下:

 

package jansonDemo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.util.*;

public class TestJsonToExcel {
    public static void main(String[] args) {
        XSSFWorkbook workbook;
        XSSFSheet sheet;
        XSSFRow row;
        XSSFCell cell;

        //創建excel工作薄
        workbook = new XSSFWorkbook();
        //創建一個工作表sheet
        sheet = workbook.createSheet("stationInfo");
        //創建第一行
        row = sheet.createRow(0);
        //創建一個單元格
        cell = null;

        //定義標題欄,放到數組中
        String stationInfo_title[] =
                {"Pictures","StationLng","SiteGuide","Address","ServiceTel",
                        "SupportOrder","OperatorID","StationID","Remark"};

        //在第一行插入標題欄
        for (int i=0;i<stationInfo_title.length;i++) {
            cell = row.createCell(i);
            cell.setCellValue(stationInfo_title[i]);
        }

        //接着從第二行開始寫入內容:
        //根據標題欄中的字段篩選相應的值,並非是獲取所有接口返回的值
        CommonFunc cf = new CommonFunc();
        try {
            int rownum = 1;
            String cellContent = "";
            JSONObject decrptobj = cf.getStationInfo(); //獲取從接口返回的json對象
            JSONArray stationArray = decrptobj.getJSONArray("StationInfos"); 
            JSONArray sortedstationArray = sortJsonArray(stationArray,"StationID"); //調用排序方法,對json數組中的對象排序
            for (int j=0; j<sortedstationArray.size(); j++) {
                row = sheet.createRow(rownum); //json數組中有多少對象就依次為每個對象創建一行
                JSONObject bodyObj = sortedstationArray.getJSONObject(j);
                for (int k=0; k<stationInfo_title.length; k++) {
                    cellContent = bodyObj.getString(stationInfo_title[k]);
                    cell = row.createCell(k); //創建單元格,即生成每行對應的列,新的一行每個單元格從0計數
                    cell.setCellValue(cellContent); //給每行的單元格賦值,組成每列的值
                }
                rownum ++;
            }

        }catch (Exception e) {
            e.printStackTrace();
        }


        //創建一個文件
        File file = new File("D:\\javaExample\\file\\stationInfo.xlsx");
        try {
            if(!file.exists()) {
                file.createNewFile();
            }
            //創建輸出流
            OutputStream outputStream = new FileOutputStream(file);
            //將拼好的內容通過輸出流寫到excle
            workbook.write(outputStream);
            //關閉輸出流
            outputStream.close();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    //專門寫一個對JSONArray排序的方法
    public static JSONArray sortJsonArray(JSONArray jsonArray, final String sortKey) {
        List<JSONObject> list = new ArrayList<>();
        for (int i=0; i<jsonArray.size(); i++) {
            list.add(jsonArray.getJSONObject(i));
        }
        Collections.sort(list, new Comparator<JSONObject>() {
            String key = sortKey;
            @Override
            public int compare(JSONObject o1, JSONObject o2) {
                String str1 = o1.getString(key);
                String str2 = o2.getString(key);
                return str1.compareTo(str2);
            }
        });
        //先清空原有數組
        jsonArray.clear();

        //將排序好的JSONObject放到JSONArray里
        for (int j=0; j<list.size(); j++) {
            jsonArray.add(list.get(j));
        }

        return jsonArray;
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM