반응형
package com.lsj.chatting;
import org.json.JSONArray;
import org.json.JSONObject;
public class testing {
public static void main(String[] args) {
/** JSONObject (no data) **/
JSONObject json = new JSONObject();
System.out.println("jsonFormat : " + json);
/** 이름 넣기 **/
json.put("name", "Lee");
System.out.println("jsonName : " + json);
System.out.println("name : " + json.getString("name"));
/** JSONArray (취미) **/
JSONArray hobbies = new JSONArray();
hobbies.put("soccer");
hobbies.put("basket ball");
json.put("hobbies", hobbies);
System.out.println("jsonNameHobbies : " + json);
System.out.println("jsonHobbies : " + json.getJSONArray("hobbies"));
/** 취미 + 이름 데이터 배열에 입력 **/
JSONArray people = new JSONArray();
people.put(json);
/** 키에 해당하는 값이 어떤 타입이냐에 따라 get 뒤에 붙는게 정해진다. **/
/** 이름 넣기 **/
json = new JSONObject(); // 초기화
json.put("name", "Tom");
/** JSONArray (취미) **/
hobbies = new JSONArray(); // 초기화
hobbies.put("painting");
hobbies.put("weight training");
json.put("hobbies", hobbies);
people.put(json);
System.out.println("people : " + people);
/** 최종 JSON **/
JSONObject person = new JSONObject();
person.put("members", people);
System.out.println("person : " + person);
/** 사람 출력 **/
JSONArray members = person.getJSONArray("members");
JSONObject member0 = members.getJSONObject(0);
JSONObject member1 = members.getJSONObject(1);
System.out.println("member0 : " + member0);
System.out.println("member1 : " + member1);
/** 취미 출력 **/
JSONArray member0Hobbies = member0.getJSONArray("hobbies");
System.out.println("member0Hobbies : " + member0Hobbies);
String member0Hobbie = member0Hobbies.getString(0);
System.out.println("member0Hobbie : " + member0Hobbie);
member0Hobbie = (String) member0Hobbies.get(1);
System.out.println("member0Hobbie : " + member0Hobbie);
// person : {"members":[{"hobbies":["soccer","basket ball"],"name":"Lee"},{"hobbies":["painting","weight training"],"name":"Tom"}]}
// 일반적 JSON 구조
}
}
반응형
'[Java] > [Java Code]' 카테고리의 다른 글
[Java Code] Pagination Select Box (0) | 2022.02.18 |
---|---|
[Java Code] Pagination (0) | 2022.02.18 |
[Java Code] 파일 읽어 데이터 가져오기 (0) | 2022.02.12 |
[Java Code] POST, Get, Delete 통신 (body 데이터 담아서 통신, body 내용 읽기) [HTTP] (0) | 2022.02.02 |
[Java Code] URLEncode, URLDecode 인코딩 변경하기 (0) | 2021.12.27 |