리플렉션을 이용한 json 직렬화

2022. 12. 28. 22:13자바멘토링

jackson 으로 진행 

 

package hello.hellospring.jsontest;

public class Dog {
    private static final String CATEGORY ="동물";

    public String name;
    public int age;


    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    private Dog() {
        this.name = "누렁이";
        this.age=0;

    }

    public Dog(final String name) {
        this.name =name;
        this.age =0;
    }
    public Dog(final String name, final int age) {
        this.name=name;
        this.age=age;

    }

    //메소드
    private void speak(final String sound, final int count) {

        System.out.println(sound.repeat(count));

    }


    public void eate() {
        System.out.println("사료를 먹습니다.");

    }


}
package hello.hellospring.jsontest;



import com.fasterxml.jackson.databind.ObjectMapper;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class DogSample {

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

        ObjectMapper mapper = new ObjectMapper();

        Class<?> clazz = Dog.class;
        Constructor<?> constructor1 = clazz.getDeclaredConstructor();//기본생성자를 Constructor 객체로 가져올수 있다.
        Constructor<?> constructor2 = clazz.getDeclaredConstructor(String.class);// 파라미터 값
        Constructor<?> constructor3 = clazz.getDeclaredConstructor(String.class, int.class);//두가지 타입의 파라미터 값을 가진 생성자 가져올수 있다.

        //생성자로 객체를 생성
        //Object dog1 = constructor1.newInstance(); //하지만 생성자가 접근제어자라 private이라 접근이 불가

        //접근 제어자가 public이 아닌 경우 setAccessible 메소드를 이용하면 접근 할 숭있다.

        constructor1.setAccessible(true);
        constructor3.setAccessible(true);
        Object dog1 = constructor1.newInstance();
        Object dog2 = constructor2.newInstance("호두");
        Object dog = constructor3.newInstance("호두", 5);



        String jsonInString01 =null;

        try {

            // 객체를 JSON 타입의 파일로 변환
            mapper.writeValue(new File("dog.json"), dog);

            // 객체를 JSON 타입의 String으로 변환
            jsonInString01  = mapper.writeValueAsString(dog);
            System.out.println(jsonInString01);


        } catch (JsonGenerationException e) {
            e.printStackTrace();
        }




    }
}
{"name":"호두","age":5}

Process finished with exit code 0

package hello.hellospring.jsontest;

import java.io.File;
import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonExample02 {

    public static void main(String[] args) {

        ObjectMapper mapper = new ObjectMapper();
        Dog dog = null;//빈 객체 생성 

        try {

            // JSON 타입의 파일을 객체로 변환

            dog = mapper.readValue(new File("Dog.json"), Dog.class);//파일 읽어오기 
            System.out.println(dog);


        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Dog{name='호두', age=5}

Process finished with exit code 0

참고:https://www.youtube.com/watch?v=t2DkuxVOw0E

https://www.lesstif.com/java/java-json-library-jackson-24445183.html

 

Java Json library jackson 사용법

2.7 버전부터는 JDK 7 이상이 필요하며 JDK6 을 지원하는 마지막 버전은 2.6.7.1 임

www.lesstif.com

https://ebabby.tistory.com/4

 

[Java] 리플렉션 (reflection) 개념 이해하기

리플렉션 들어가며 자바를 처음 배우던 시절 생각해 보면 리플렉션이라는 단어조차 들어 본 적이 없었습니다. 자바를 점점 학습하면서 종종 들어봤지만 그때 당시 '리플렉션을 모르면 사용하지

ebabby.tistory.com

https://kim-jong-hyun.tistory.com/22

'자바멘토링' 카테고리의 다른 글

TCP/IC  (0) 2023.01.06
Future을 이용한 비동기 프로그래밍  (0) 2023.01.01
파일디스크립터  (0) 2022.12.18
리플렉션  (0) 2022.12.15
Try - With - Resource  (0) 2022.12.04