Back-end/Java, Kotlin

json인듯 아닌듯 한 데이터를 jsonParsing하기

philo0407 2021. 3. 14. 23:53

 

여러 개의 파일을 읽어 들여서

json인듯 아닌듯 한 파일을 읽어서 json 데이터로 가공한 뒤에

json으로 읽어서 특정 조건에 맞는 데이터를 추출한 다음에

엑셀 장표에 옮기면 된다.

 

 

package jsonParser;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FilenameFilter;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class 파일리스트 {
	public static void main(String[] args) throws FileNotFoundException {
		File path = new File("sampleFileList/");
		final String pattern = "delete";
		
		System.out.println(path.getAbsolutePath());
		System.out.println(path.getPath());
		
		String fileList[] = path.list(new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				return name.startsWith(pattern);
			}
		});
		
		String line = "";
		StringBuffer sb = new StringBuffer("");
		if(fileList.length > 0) {
			for(int i=0; i< fileList.length; i++) { // 파일 하나씩 읽기
				System.out.println(fileList[i]);
				
				try(FileReader fr = new FileReader(path.getAbsolutePath()+"/"+fileList[i]);
						BufferedReader br = new BufferedReader(fr)) {
					for(int j=0; (line = br.readLine()) != null; j++) {
						System.out.println(line);
						if(i==0 && j==0) { // 처음 파일의 처음부분만 parsing해야한다.
							sb.append(line);
						} else {
							sb.append(", "+line);
						}
					}
				} catch(Exception e) {
					e.printStackTrace();
				}
			}
		}
		
		System.out.println("=============================================================");
		String newStr = "[" + sb.toString().replaceAll("\"", "\\\"") + "]";
		System.out.println(newStr);
		System.out.println("=============================================================");
		
		try {
			JSONParser jsonParser = new JSONParser();
			JSONArray jsonArray = (JSONArray) jsonParser.parse(newStr);
			System.out.println("jsonArray.size(): " +jsonArray.size());
			for(int i=0; i<jsonArray.size(); i++) {
				JSONObject jsonObj = (JSONObject) jsonArray.get(i);
				JSONObject jsonObj_depth_2 = (JSONObject) jsonObj.get("sendDate");
				String day = String.valueOf(jsonObj_depth_2.get("date"));
				if(day.equals("12")) {
					System.out.println("day: " +day);
				}
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}
}

 

 

일단 중간 완성한 건데... 좀 못생기게 짰다 ㅠ 나중에 리펙하자.