studying...
  • 노트의목적
  • 웹전반
    • HTTP
      • 1. HTTP
      • 2. HTTP_Client
      • 3. HTTP_Server
      • 4. JAVA_HTTP_Server
      • 5. Spring_Web_MVC
    • REST_API
      • 1. REST_API
      • 2. URI&MIME_type
      • 3. COLLECTION_Pattern
      • 4. COLLECTION_Pattern_adjustment
      • 5. Spring_Web_MVC
    • DTO_JSON_CORS
      • 1. DTO
      • 2. 직렬화
      • 3. Jackson
      • 4. CORS
    • Layered_Architecture
      • 1. Layered_Architecure
      • 2. Data_Access
      • 3. Domain_Model
    • DI&Spring_Test
      • 1. Dependency_Injection
      • 2. Unit_Test
      • 3. Spring_Test
      • 4. TDD
    • Database
      • 1. Database
      • 2. Relational_Model
      • 3. JDBC
    • JPA
      • 1. ORM
      • 2. Hibernate
      • 3. Embeddable
      • 4. Relationship Mapping
      • 5. Spring Data JPA
    • 도메인_주도_설계
      • 1. DDD
      • 2. Strategic Design
      • 3. Entity, Value Object
      • 4. Aggregate
      • 5. Repository
    • Hexagonal_Architecture
      • 1. SOLID
      • 2. Hexagonal_Architecture
      • 3. 도메인 주도 설계 핵심
    • Spring_Security
      • 1. 애플리케이션 보안
      • 2. 인증
      • 3. 로그인 & 로그아웃
      • 4. 회원가입
      • 5. JWT&Authority
    • File_Upload
      • 1. Multipart_FormData
      • 2. Separation_of_Concerns
      • 3. Cloudinary
    • CQRS
      • 1. CQRS
      • 2. Redis
  • 면접대비
  • book
    • RealMySQL8.0
      • 4장
      • 5장
      • 8장
      • 9장
    • Object
      • 1장
      • 2장
      • 3장
      • 4장
      • 5장
      • 6장
      • 7장
      • 8장
      • 9장
    • ModernJava
      • ch1
      • ch2
    • 클라우드네이티브를위한 쿠버네티스 실전 프로젝트
      • 1장
      • 2장
      • 3장
      • 4장
    • 테라폼 쿡북
      • 2장
      • 3장
      • 4장
      • 5장
      • 6장
  • lecture
    • 외워서끝내는네트워크기초
    • 외워서끝내는네트워크심화
    • aws
      • Architecting_on_AWS
      • Architecrting-advanced
      • Developing_on_AWS
      • migration_essentials
      • Resilience
      • Running_Containers_on_EKS
    • Ansible
    • k8s
      • section2
      • section3
    • Terraform
  • experiences
    • workshops
      • EKS
Powered by GitBook
On this page
  • Jackson ObjectMapper란
  • @JsonProperty
  1. 웹전반
  2. DTO_JSON_CORS

3. Jackson

Previous2. 직렬화Next4. CORS

Last updated 1 year ago

Jackson ObjectMapper란

자바용 JSON 라이브러리로 주로 쓰이지만 xml, yaml, csv 등의 다양한 데이터 직렬화를 제공하는 툴

자바 어플리케이션에서 단일로 사용한다면 객체를 생성해서 사용하면 되고

public class Car {
    private String color;
    private String type;
    // standard getters setters
}

public static void main() {
    ObjectMapper objectMapper = new ObjectMapper();
    Car car = new Car("yellow", "renault");
    objectMapper.writeValue(new File("target/car.json"), car);
}

스프링을 사용한다면 스프링 웹에 기본으로 포함되어 있어서

public class PostController {
	private final ObjectMapper objectMapper;
	
	public PostController(ObjectMapper objectMapper) {
		this.objectMapper = objectMapper;
	}
}

@GetMapping("/{id}")
public String detail(@PathVariable String id) throws JacksonException {
    PostDto postDto = new PostDto(id, "제목", "내용");
    
    return objectMapper.writeValueAsString(postDto);
}

의존성 주입으로 바로 사용할 수 있다. 물론 이렇게 사용해서 JSON을 변환할 수도 있지만 컨트롤러에 쓰는 어노테이션을 다시보면

@CrossOrigin
@RestController
@RequestMapping("posts")

이 세가지 중 @RestController에는

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody

@ResponseBody가 존재하는데 이 어노테이션은 컨트롤러에게 객체가 자동으로 JSON으로 변환되어 돌아가도록 명령한다.

물론

@PostMapping(value = "/content", produces = MediaType.APPLICATION_XML_VALUE)

위와 같이 리턴 타입을 지정할 수도 있다.

@JsonProperty

자바 객체를 직렬화할 때 이름을 지정해주기 위한 어노테이션으로 기본적으로 직렬화된 JSON 객체는 get메서드의 이름을 따르는데

public class PostDto {
    private String id;
    private String title;
    private String content;

    public PostDto() {
    }

    public PostDto(String id, String title, String content) {
        this.id = id;
        this.title = title;
        this.content = content;
    }

    public String getId() {
        return id;
    }

    public String getTitle() {
        return title;
    }

    public String gethelloContent() {
        return content;
    }
}

실제로 DTO를 위와 같이 만들고 요청을 보내면

demo-rest-api % curl -X POST localhost:8080/posts -d '{"title": "제목"}' -H 'Content-Type: application/json'
{"id":null,"title":"제목","helloContent":null}%     

get에 맞춘 다음과 같은 응답이 오게 된다. 이걸 명시하려면

private String id;
private String title;
@JsonProperty("modifiedHelloContent")
private String content;

필드에 @JsonProperty를 적어주면 된다.

그럼 응답이 이렇게 온다.

demo-rest-api % curl -X POST localhost:8080/posts -d '{"title": "제목"}' -H 'Content-Type: application/json'
{"id":null,"title":"제목","modifiedHelloContent":null}%   

출처

baeldung
Jackson ObjectMapper란
@JsonProperty