728x90
// JSON 문자열
String jsonString = "{"
+ "\"name\": \"John Doe\","
+ "\"age\": 30,"
+ "\"address\": \"123 Main Street, Anytown, CA 12345\""
+ "}";
// JSON 문자열을 JSONObject 객체로 변환
JSONObject jsonObject = new JSONObject(jsonString);
//1. get() 메서드로 이름 속성의 값만 가져오기
String name = jsonObject.get("name");
System.out.println("이름: " + name);
//2. keySet() 메서드로 항목 전체 출력
Set<String> keys = jsonObject.keySet();
for (String key : keys) {
System.out.println(key);
}
//3. entrySet() 메서드로 항목 전체 출력
Set<Map.Entry<String, Object>> entries = jsonObject.entrySet();
for (Map.Entry<String, Object> entry : entries) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
//4. JSON 문자열로 변환
String jsonString2 = jsonObject.toString();
System.out.println(jsonString2);
- get()
- keySet()
- entrySet()
//출력결과
이름: John Doe
name: John Doe
age: 30
address: 123 Main Street, Anytown, CA 12345
name: John Doe
age: 30
address: 123 Main Street, Anytown, CA 12345
{"name":"John Doe","age":30,"address":"123 Main Street, Anytown, CA 12345"}
보면 좋을 다른 포스팅 :
https://rebornbb.tistory.com/entry/JAVA-JSON-to-String-String-to-JSON
728x90