ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [JAVA] SELECT 로 가져온 데이타를 .json 파일로 변환하기 및 에러처리
    WEB/BACK 2021. 6. 3. 17:00
    반응형

     

     

     

     

     

    안녕하세요 오늘은 필요한 데이터를 조회해서 그 결과를 json 파일로 떨구는 작업을 진행해보도록 하겠습니다.

    만약 여러분이 hashMap을 만들지 않고 예를 들어 아래와같이 

    JSONObject jj = new JSONObject();
    jj.("a","apple");
    jj.("b", "banana");

    바로 JSONObject에다가 put을 하게되면 마주치게 되는 에러가 있습니다.

     

    Type safety: The method put(Object, Object) belongs to the raw type HashMap. References to generic type HashMap<K,V> should be parameterized

    (형식 안전성 : put (Object, Object) 메서드는 원시 형식 HashMap에 속합니다. 제네릭 형식 HashMap <K, V>에 대한 참조는 매개 변수화해야합니다.)

    Type safety: The method add(Object) belongs to the raw type ArrayList. References to generic type ArrayList<E> should be parameterized

    (형식 안전성 : add (Object) 메서드는 원시 형식 ArrayList에 속합니다. 제네릭 형식 ArrayList <E>에 대한 참조는 매개 변수화해야합니다.)

     

     

    물론 그냥 이 상태로도 돌아가긴 하지만 hashMap을 만들어서 없애주도록 하겠습니다.

     

    import java.util.HashMap;
    import org.json.simple.JSONArray;
    import org.json.simple.JSONObject;
    
    public class JSONTest {
    
    public static void main(String[] args) {
    
          //1. hashMap 생성 및 데이터 추가
          HashMap<String, Object> hashMap = new HashMap<String, Object>();
          hashMap.put("a", "apple");
          hashMap.put("b", "banana");
    
          System.out.println(hashMap+" =hashMap"); //{a=apple, b=banana}
    
          //2.중괄호
          JSONObject jsonObj = new JSONObject(hashMap); 
          System.out.println(jsonObj+" =jsonObj"); //{"a":"apple","b":"banana"}
    
          //3.대괄호
          JSONArray jsonArr = new JSONArray(); 
          jsonArr.add(jsonObj);
          System.out.println(jsonArr+" =jsonArr"); //[{"a":"apple","b":"banana"}]
    
          //4.감싸는 이름을 정의함 
          HashMap<String, Object> hashMap2 = new HashMap<String, Object>();
          hashMap2.put("English",jsonArr);
          JSONObject jsonName = new JSONObject(hashMap2); 
    
          System.out.println(jsonName+" =jsonName"); //{"English":[{"a":"apple","b":"banana"}]}
    
          }
    
    }
    

     

    거기다가 원하는 폴더에 json파일로 떨구기까지 해보겠습니다.

     

    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.HashMap;
    
    import org.json.simple.JSONArray;
    import org.json.simple.JSONObject;
    
    public class JSONTest {
    
      public static void main(String[] args) throws IOException {
    
        //1. hashMap 생성 및 데이터 추가
        HashMap<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("a", "apple");
        hashMap.put("b", "banana");
    
        System.out.println(hashMap+" =hashMap"); //{a=apple, b=banana}
    
        //2.중괄호
        JSONObject jsonObj = new JSONObject(hashMap); 
        System.out.println(jsonObj+" =jsonObj"); //{"a":"apple","b":"banana"}
    
        //3.대괄호
        JSONArray jsonArr = new JSONArray(); 
        jsonArr.add(jsonObj);
        System.out.println(jsonArr+" =jsonArr"); //[{"a":"apple","b":"banana"}]
    
        //4.감싸는 이름을 정의함 
        HashMap<String, Object> hashMap2 = new HashMap<String, Object>();
        hashMap2.put("English",jsonArr);
        JSONObject jsonName = new JSONObject(hashMap2); 
    
        System.out.println(jsonName+" =jsonName"); //{"English":[{"a":"apple","b":"banana"}]}
    
    
        String file_name = "";
        SimpleDateFormat format1 = new SimpleDateFormat ( "yyyy-MM-dd");
        Date time = new Date();
        String time1 = format1.format(time);
    
    
        //파일 이름 생성 현재시간+랜덤숫자
        SimpleDateFormat time_now_secon = new SimpleDateFormat("yyyy_MM_dd_HHmmssSSS");
        int rndNum = (int)(Math.random()*100000);
        file_name = time_now_secon.format(new Date(System.currentTimeMillis()))+"_"+rndNum;
        String dir = "C:\\Users\\test\\";
    
        //디렉토리가 존재하지 않는다면 생성
        File destdir = new File(dir); //디렉토리 가져오기
    
        if(!destdir.exists()){
        destdir.mkdirs(); 
        }
    
    
        //내컴퓨터에 json파일로 저장
        FileWriter file = new FileWriter(dir+file_name+".json");
        file.write(jsonName.toJSONString());//
        file.flush();
        file.close();
    
    
      }
    
    }
    

     

    json

     

    파일 확인 끝

     

     

     

     

     

     

     

     

     

     

     

     

     

    반응형

    댓글

Designed by Tistory.