嵌套JSON动态数据转换为xls或csv文件

时间:2018-07-26 04:50:03

标签: java json export-to-excel export-to-csv

我有一个JSON文件,我需要将其转换为excel或csv文件。

JSON文件:

 {

  "gstin": "37AAACGJSJOSFF",
  "fp": "032018",
  "b2b": [
    {
      "ctin": "33ASADKSDMK",
      "cfs": "Y",
      "cname": null,
      "inv": [
        {
          "itms": [
            {
              "num": 500,
              "itm_det": {
                "csamt": 0,
                "rt\n": 5,
                "txval": 0,
                "iamt": 0
              }
            }
          ],
          "val": 87004,
          "inv_typ": "R",
          "pos": "37",
          "idt": "31-03-2018",
          "rchrg": "Y",
          "inum": "S78",
          "chksum": "13e230e9ednaskdjslsd23ea83a50cafbf675a111b"
        }
      ]
    },
    {
      "ctin": "37ADJKSKSF';DF",
      "cfs": "Y",
      "cname": null,
      "inv": [
        {
          "itms": [
            {
              "num": 1,
              "itm_det": {
                "csamt": 0,
                "samt": 3092.64,
                "rt": 18,
                "txval": 34362.7,
                "camt": 3092.64
              }
            }
          ],
          "val": 40548,
          "inv_typ": "R",
          "pos": "37",
          "idt": "05-03-2018",
          "rchrg": "N",
          "inum": "200/AASDS/IKJO/RSJ",
          "chksum": "66395159aac02dfe3dfadkjasdlkbbafde86c9e27aa0fb1605ebbe"
        },
        {
          "itms": [
            {
              "num": 1,
              "itm_det": {
                "csamt": 0,
                "samt": 68429.97,
                "rt": 18,
                "txval": 760332.99,
                "camt": 68429.97
              }
            }
          ],
          "val": 897193,
          "inv_typ": "R",
          "pos": "37",
          "idt": "03-03-2018",
          "rchrg": "N",
          "inum": "235/HSLFA/IASDKC/DSKF",
          "chksum": "8b60e669ee6156e0ajhaf42e4189aabbb57245127c4e609d8e"
        },
        {
          "itms": [
            {
              "num": 1,
              "itm_det": {
                "csamt": 0,
                "samt": 84846.74,
                "rt": 18,
                "txval": 942741.6,
                "camt": 84846.74
              }
            }
          ],
          "val": 1114535,
          "inv_typ": "R",
          "pos": "37",
          "idt": "03-03-2018",
          "rchrg": "N",
          "inum": "236/HNSsdkfs/IsdkdC/Vsdkj",
          "chksum": "eb5110c0047adsdsd63cfedc686e3e84c9a5d9c126cb96d99645"
        },
        {
          "itms": [
            {
              "num": 1,
              "itm_det": {
                "csamt": 0,
                "samt": 348.13,
                "rt": 18,
                "txval": 8312.57,
                "camt": 648.13
              }
            }
          ],
          "val": 452609,
          "inv_typ": "R",
          "pos": "37",
          "idt": "03-03-2018",
          "rchrg": "N",
          "inum": "237/HNSdf/Isdxf/Rdf",
          "chksum": "8181aa8d52d4c9d58csdsf915e0f4955e48c59f57f21d799f51e117c6"
        },
        {
          "itms": [
            {
              "num": 1,
              "itm_det": {
                "csamt": 0,
                "samt": 68429.97,
                "rt": 18,
                "txval": 760333,
                "camt": 68429.97
              }
            }
          ],
          "val": 897193,
          "inv_typ": "R",
          "pos": "37",
          "idt": "31-03-2018",
          "rchrg": "N",
          "inum": "269/HNSSA/IsfsfC/Kdf",
          "chksum": "2a46181337bdgdg88cbdfec8f3322718f029fd9d8d96e3481"
        },
        {
          "itms": [
            {
              "num": 1,
              "itm_det": {
                "csamt": 0,
                "samt": 94438.83,
                "rt": 18,
                "txval": 1049320.3,
                "camt": 94438.83
              }
            }
          ],
          "val": 1238198,
          "inv_typ": "R",
          "pos": "37",
          "idt": "31-03-2018",
          "rchrg": "N",
          "inum": "271/HNSSA/Isfsf/Vada",
          "chksum": "be96bd7d39b4773e599dd5sfsf1b0cad152092777271590a76f8dcb6f"
        },
        {
          "itms": [
            {
              "num": 1,
              "itm_det": {
                "csamt": 0,
                "samt": 37297.41,
                "rt": 18,
                "txval": 414415.71,
                "camt": 37297.41
              }
            }
          ],
          "val": 489011,
          "inv_typ": "R",
          "pos": "37",
          "idt": "31-03-2018",
          "rchrg": "N",
          "inum": "272/HNSSA/Isdfs/RsfJ",
          "chksum": "684604977sdfsf304sfdsf12e3d82bee08705b675d5ccacad546"
        },
        {
          "itms": [
            {
              "num": 1,
              "itm_det": {
                "csamt": 0,
                "samt": 283.99,
                "rt": 18,
                "txval": 3155.42,
                "camt": 283.99
              }
            }
          ],
          "val": 3723,
          "inv_typ": "R",
          "pos": "37",
          "idt": "03-03-2018",
          "rchrg": "N",
          "inum": "286/HsfdS/Isfs/Kadd",
          "chksum": "ef28779994414cf8sfsf7797bff799b5c9dda1f29a21cdb89112f2a843"
        }
      ]
    }
  ]
}

输出为: enter image description here

我的方法:

我使用简单的JSON jar解析数据,并尝试通过考虑三种情况JSON对象或JSON数组或一个String来写入值,而我正通过这种方式将其写入csv文件列,我面临的问题是数据是动态的,因此在inv下位于itms_det下int下inv的第一个对象的b2b数据中,只有四行,因此在第二个对象中我有5行,因此在我的输出中,如果您在第一行中观察到b2b__inv__itms__itm_det__samt下没有值,那是因为第一个对象没有没有该字段,所以我面临着生成csv文件头并将其相应放置的问题。是否有其他替代方法可以在java中做到这一点,也没有其他方法也可以,欢迎任何建议或帮助。

我的代码:

package json2csvdynamic;

import com.sun.xml.internal.ws.util.StringUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.json.CDL;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

/**
 *
 * @author 00511175
 */
public class Json2csvdynamic {

    HSSFWorkbook workBook = new HSSFWorkbook();
    HSSFSheet sheet = workBook.createSheet();
    HSSFRow row;
    int i;
    public int col;

    public HSSFRow getRow() {
        return row;
    }

    public void setRow(HSSFRow row) {
        this.row = row;
    }

    public int getI() {
        return i;
    }

    public void setI(int i) {
        this.i = i;
    }

    /**
     * @param args the command line arguments
     */
    public void excelproccessing(ArrayList arr, HSSFSheet sheet, String prev_key) {

        if (col < 20) {
            int j = 0;
            for (i = 0; i < arr.size(); i++) {
//            if (col != 0) {
//                jsexcel.row = jsexcel.sheet.getRow(0);
//                jsexcel.row = jsexcel.sheet.getRow(1);
//            }
                row = sheet.getRow(j);
                if (row == null) {
                    sheet.createRow(j);
                    row = sheet.getRow(j);
                }

                if (i == 0) {
                    if (prev_key.equalsIgnoreCase("") || prev_key.equals(null)) {
                        row.createCell(col).setCellValue((String) arr.get(i));
                    } else {
                        row.createCell(col).setCellValue(prev_key);
                    }

                } else {
                    row.createCell(col).setCellValue((String) arr.get(i));
                }
                j++;

            }
            col = col + 1;
//        System.out.println("a::" + a);

        }
    }

    public void arrayexcelprocessing(org.json.simple.JSONArray jsonarr, HSSFSheet sheet, String prev_key) {
        int j = 0;

        for (i = 0; i < jsonarr.size(); i++) {

//            row = sheet.getRow(j);
//            if (row == null) {
//                sheet.createRow(j);
//                row = sheet.getRow(j);
//            }
////            row.createCell(col).setCellValue(jsonarr.get(i).toString());
//            j++;
            org.json.simple.JSONObject jsonObject = (org.json.simple.JSONObject) jsonarr.get(i);
            for (Iterator iterator = jsonObject.keySet().iterator();
                    iterator.hasNext();) {
                String key = (String) iterator.next();
                System.out.println("the level2 keys" + key);
                Object obj = jsonObject.get(key);
                if (obj instanceof JSONArray) {
                    org.json.simple.JSONArray jsonarr1 = (org.json.simple.JSONArray) obj;

                    arrayexcelprocessing(jsonarr1, sheet, prev_key.concat("/").concat(key));

                } else if (obj instanceof JSONObject) {
                    for (iterator = ((org.json.simple.JSONObject) obj).keySet().iterator();
                            iterator.hasNext();) {
                        String key1 = (String) iterator.next();
                        Object obj1 = ((org.json.simple.JSONObject) obj).get(key1);
                        ArrayList<String> arr = new ArrayList<String>();
                        //   String FileName = "json.csv";
                        arr.add(key1);

                        arr.add(String.valueOf(obj1));
                        if (col < 20) {
                            excelproccessing(arr, sheet, prev_key.concat("/").concat(key1));
                        }

                    }

                    System.out.println("obj" + obj.toString());

                } else {
                    ArrayList<String> arr = new ArrayList<String>();
                    //   String FileName = "json.csv";
                    arr.add(key);
                    arr.add(String.valueOf(obj));
                    if (col < 20) {
                        excelproccessing(arr, sheet, prev_key.concat("/").concat(key));
                    }

                }

            }
        }

    }

    public static void main(String[] args) throws IOException, ParseException {

        Json2csvdynamic jsexcel = new Json2csvdynamic();

        JSONParser parser = new JSONParser();
        org.json.simple.JSONObject jsonObject = (org.json.simple.JSONObject) parser.parse(new FileReader("C:\\Users\\workspace\\json2csv\\test.json"));
        for (Iterator iterator = jsonObject.keySet().iterator();
                iterator.hasNext();) {

            String key = (String) iterator.next();
            System.out.println("the level1 keys" + key);
            Object obj = jsonObject.get(key);

            if (obj instanceof JSONArray) {
                org.json.simple.JSONArray jsonarr = (org.json.simple.JSONArray) obj;

                jsexcel.arrayexcelprocessing(jsonarr, jsexcel.sheet, key);

            } else if (obj instanceof JSONObject) {

                org.json.simple.JSONObject jo = (org.json.simple.JSONObject) obj;
            } else {

                ArrayList<String> arr = new ArrayList<String>();
                //   String FileName = "json.csv";
                arr.add(key);
                arr.add((String) obj);

                jsexcel.excelproccessing(arr, jsexcel.sheet, "");

            }

        }
        FileOutputStream out
                = new FileOutputStream(new File("C:\\Users\\workspace\\json2csv\\test.xls"));

        jsexcel.workBook.write(out);

        out.close();
    }

}

0 个答案:

没有答案