Post

Java에서 DTO를 이용하여 JSON 만들기

1. Dependency 설정

1
2
3
4
5
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.14.1</version>
</dependency>

2. JSON 생성 예제

  • JsonGenerate.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import com.example.json.dto.JsonDto;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JsonGenerate {
    public static void main(String[] args) {

        JsonDto jsonDto = new JsonDto();
        jsonDto.setUserId("uid");
        jsonDto.setUserName("홍길동");

        List<String> hobbyList = new ArrayList<>();
        hobbyList.add("축구");
        hobbyList.add("야구");
        hobbyList.add("농구");
        jsonDto.setHobbyList(hobbyList);

        Map<String, Object> data = new HashMap<>();
        data.put("data", jsonDto);

        try {
            String json = new ObjectMapper().writeValueAsString(data);
            System.out.println(json);

        } catch (Exception e) {
            e.getMessage();
        }
    }
}
  • JsonDto
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.util.List;

@Getter
@Setter
@NoArgsConstructor
public class JsonDto {
    private String userId;
    private String userName;
    private List<String> hobbyList;
}
  • 결과
1
2
3
4
5
6
7
{
    "data": {
        "userId": "uid",
        "userName": "홍길동",
        "hobbyList": ["축구", "야구", "농구"]
    }
}

[출처 및 참고]

This post is licensed under CC BY 4.0 by the author.