json to csv

给定json格式如下
[{
“duration”: 2100,
“appid”: “weixin”,
“page”: “first page”,
“app_ver_name”: “4.2.1”
},
{
“duration”: 3402,
“appid”: “qq”,
“page”: “first page”,
“app_ver_name”: “10.5.2”
},
{
“duration”: 1002,
“appid”: “qq”,
“page”: “first page”,
“app_ver_name”: “11.0.5”,
“access_num”: 34
}]
要求: 将其存储为csv格式, 再将csv格式的数据转为json格式, 转出的json格式要与输入的json一致

public class CSV2Json {

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

		String filename = "orderLines.csv";
		String filetype = filename.substring(filename.lastIndexOf(".") + 1);
		String filepath = "D:/" + filename;
		String json = null;

		if (filetype.equals("csv")) {

			File input = new File(filepath);
			CsvSchema csvSchema = CsvSchema.builder().setUseHeader(true).build();
			CsvMapper csvMapper = new CsvMapper();

			// 读CSV文件
			List<Object> readAll = csvMapper.readerFor(LinkedHashMap.class).with(csvSchema).readValues(input).readAll();
			List<HashMap<String, Object>> newdata = new ArrayList<HashMap<String, Object>>();
			for (Object r : readAll) {
				Map<String, Object> tmp = (Map<String, Object>) r;
				Map<String, Object> m = new LinkedHashMap<String, Object>();
				for (Entry<String, Object> entry : tmp.entrySet()) {
					if ("".equals(entry.getValue())) {
//					tmp.remove(entry.getKey());
						continue;
					}
					if (isInteger((String) entry.getValue())) {
						
						m.put(entry.getKey(), Integer.valueOf((String) entry.getValue()));
						continue;
					}
					m.put(entry.getKey(), entry.getValue());
				}
				newdata.add((HashMap<String, Object>) m);
			}
			Gson objJson = new Gson();
			json = objJson.toJson(newdata, List.class);
		}
		System.out.println(json);
		File file =new File("D:/orderLinesFromCsv.json");//json数据存储位置
		 if(!file.exists()){
	        	file.createNewFile();
	        }

		OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(file),"UTF-8");
 
		osw.write(json);
		osw.flush();
		osw.close();
 
        System.out.println("finish");
	}

	static boolean isInteger(String str) {
		Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
		return pattern.matcher(str).matches();
	}
}

你可能感兴趣的:(练习,json)