반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- windows
- list
- 정규식
- Array
- 자바스크립트
- 이클립스
- 테이블
- json
- 인텔리제이
- Java
- html
- input
- 자바
- Visual Studio Code
- vscode
- 이탈리아
- IntelliJ
- Button
- ArrayList
- javascript
- table
- Maven
- 배열
- date
- js
- 문자열
- string
- CMD
- CSS
- Eclipse
Archives
- Today
- Total
어제 오늘 내일
[Java / json-simple] Map을 JSON으로 변경하기 본문
이번에는 json-simple 라이브러리를 이용하여
Map 객체를 JSONObject로 변경하는 방법을 알아보도록 하겠습니다.
라이브러리 추가하기 (MAVEN)
먼저, json-simple 라이브러리를 추가합니다.
pom.xml 파일에 아래와 같이 dependency를 추가합니다.
<dependency> <groupId>com.googlecode.json-simple</groupId> <artifactId>json-simple</artifactId> <version>1.1.1</version> </dependency>
Map -> JSONObject
코드
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.json.simple.JSONObject; public class MapToJson { public static void main(String[] args) { // professor Map<String, Object> professor = new HashMap<>(); professor.put("name", "kim"); professor.put("office", 203); // students (List<Map>) Map<String, Object> student1 = new HashMap<>(); student1.put("name", "lee"); student1.put("grade", "A"); Map<String, Object> student2 = new HashMap<>(); student2.put("name", "park"); student2.put("grade", "B"); List<Map> students = new ArrayList<>(); students.add(student1); students.add(student2); // Map에 데이터 담기 Map<String, Object> map = new HashMap<>(); map.put("major", "CS"); map.put("professor", professor); map.put("students", students); // Map -> JSON JSONObject jsonObject = new JSONObject(map); // 결과 출력 System.out.println(jsonObject); } }
결과
{ "students": [ { "grade": "A", "name": "lee" }, { "grade": "B", "name": "park" } ], "professor": { "name": "kim", "office": 203 }, "major": "CS" }
JSONObject jsonObject = new JSONObject(map);
JSONObject의 생성자로, Map 객체를 전달하여
map을 JSONObject로 변환하였습니다.
json-simple 라이브러리를 이용하여,
Map객체를 JSONObject로 변환 하는 방법에 대해서 알아보았습니다.
반응형
'IT > Java' 카테고리의 다른 글
[Java] 여러개의 Set 객체 합치기 (0) | 2021.07.17 |
---|---|
[Java / json-simple] JSON에 데이터 추가, 변경, 삭제하기 (0) | 2021.07.17 |
[Java / json-simple ] 문자열을 JSON으로 변환하기 (1) | 2021.07.17 |
[Java / json-simple ] JSON 파일 읽기 (0) | 2021.07.17 |
[Java] 배열의 중간에 새로운 값 추가하기 (0) | 2021.07.17 |