[工具类] 读取解析json文件

 

读取json文件并转换为字符串

    /**
     * 通过本地文件访问json并读取
     *
     * @param path:json文件路径
     * @return:json文件的内容
     */
    public static String ReadFile(String path) {
        StringBuffer laststr = new StringBuffer();
        File file = new File(path);// 打开文件
        BufferedReader reader = null;
        try {
            FileInputStream in = new FileInputStream(file);
            reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));// 读取文件
            String tempString = null;
            while ((tempString = reader.readLine()) != null) {
                laststr = laststr.append(tempString);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException el) {
                }
            }
        }
        return laststr.toString();
    }

 

解析json(fastjson)

public static void main(String args[]) {
        String filePath = "D:/data.json";
        String jsonString = ReadFile(filePath);
        JSONArray jsonArr = JSON.parseArray(jsonString);
        Map<String, Object> resultMap = new HashMap<String, Object>();
        for (int i = 0; i < jsonArr.size(); i++) {

            Map data_map = (Map) jsonArr.get(i);//本次循环获取数据
            Integer customer_id = (Integer) data_map.get("customer_id");
            String customer_email = (String) data_map.get("customer_email");
            String customer_firstname = (String) data_map.get("customer_firstname");
            String customer_lastname = (String) data_map.get("customer_lastname");

            String sku = (String) data_map.get("sku");
            String created_at = (String) data_map.get("created_at");

            Map level_1_map = (Map) resultMap.get(customer_id.toString());
            if (null == level_1_map || level_1_map.size() <= 0) {
                level_1_map = new HashMap<String, Object>();
                level_1_map.put("customer_id", customer_id);
                level_1_map.put("customer_email", customer_email);
                level_1_map.put("customer_firstname", customer_firstname);
                level_1_map.put("customer_lastname", customer_lastname);
            }

            List list = level_1_map.get("list") == null ? new ArrayList<T>() : (List) level_1_map.get("list");
            Map listMap = new HashMap<String, Object>();
            listMap.put("sku", sku);
            listMap.put("created_at", created_at);
            list.add(listMap);
            level_1_map.put("list", list);

            resultMap.put(customer_id.toString(), level_1_map);
        }
        System.out.println(JSON.toJSONString(resultMap));


    }

 

posted @ 2018-07-12 09:14  Aviva_ye  阅读(2271)  评论(0编辑  收藏  举报