dependency
// gradle
// https://mvnrepository.com/artifact/org.json/json
implementation group: 'org.json', name: 'json', version: '20230227'
// maven
<!-- org.json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180813</version>
</dependency>
JSONObject
public class RunTestController {
public static void main(String[] args) throws Exception {
/**
* Json 넣기
*/
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", "흰둥이");
jsonObject.put("password", "1234");
jsonObject.put("addr", "대한민국");
jsonObject.put("age", "1");
System.err.println(jsonObject);
}
}
Pretty Print 예쁘게 출력하기
/**
* pretty print 예쁘게 출력하기
* jsonObject.toString(4) <- 숫자는 간격을 의미함
* 0은 한줄
* 1부터는 아래로 정렬해서 띄어쓰기가 들어감
*/
System.err.println("jsonObject.toString(4) : ");
System.err.println(jsonObject.toString(4));
Parsing 파싱하기1
/**
* org.json parsing 하기
*/
String jsonText = "{\"id\":\"흰둥이\",\"password\":\"1234\",\"addr\":\"대한민국\",\"age\":1}";
JSONObject jo = new JSONObject(jsonText);
String id = jo.getString("id");
String password = jo.getString("password");
String addr = jo.getString("addr");
int age = jo.getInt("age");
System.err.println("id : "+id);
System.err.println("password : "+password);
System.err.println("addr : "+addr);
System.err.println("age : "+age);
Parsing 파싱하기2
String jsonText2 =
"{"
+ "\"map1\": {"
+ "\"id\": \"흰둥이\","
+ "\"password\": \"1234\","
+ "\"addr\": \"대한민국\","
+ "\"age\": \"1\"},"
+ "\"map2\": {"
+ "\"id\": \"검둥이\","
+ "\"password\": \"5678\","
+ "\"addr\": \"제주도\","
+ "\"age\": \"2\" }"
+"}";
JSONObject jo2 = new JSONObject(jsonText2);
System.err.println(jo2.toString(4));
/**
* JSONObject 에 Json 문자열을 넣고 키값을 다시 JSONObject 에 넣어서 데이터를 가져온다
*/
JSONObject jo3 = jo2.getJSONObject("map1");
System.err.println("--------------------------");
System.err.println(jo3.toString(4));
'개발 > Java' 카테고리의 다른 글
[Java] ExcelUpload - 파일 읽고 DB에 insert 하기 (0) | 2023.05.11 |
---|---|
[Java] google json-simple 사용하기 (0) | 2023.05.08 |
[HttpsUrlConnection] 인증서 GET/POST JSON 통신 (0) | 2023.05.06 |
[Java] PriorityQueue - 우선순위 큐 (0) | 2023.04.08 |
[Java] split(regex , limit) limit 유무 차이 (0) | 2023.03.30 |
댓글