Java
JSON 파싱 연습 2단계
H_u
2024. 6. 7. 14:46
728x90
반응형
SMALL
💡 JSON Object와 JSON Array의 타입을 반드시 구분하자.
JSON Object (JSON 객체):
- JSON 객체는 { } 로 둘러싸인 키-값 쌍의 집합입니다.
- 키는 항상 문자열이고, 값은 문자열, 숫자, 객체, 배열, 불리언, 또는 null일 수 있습니다.
{
"name": "홍길동",
"age": 21,
"subjects": ["수학", "물리", "컴퓨터 과학"]
}
JSON Array (JSON 배열):
- JSON 배열은 [ ]로 둘러싸인 값의 순서 있는 목록입니다.
- 배열의 각 값은 모든 JSON 데이터 타입이 될 수 있습니다.
[
{
"name": "홍길동",
"age": 21,
"subjects": ["수학", "물리", "컴퓨터 과학"]
},
{
"name": "이순신",
"age": 22,
"subjects": ["역사", "군사학"]
}
]
문자열(String)
숫자(Number)
불리언(Boolean)
객체(Object)
배열(List)
널(Null)
https://jsonplaceholder.typicode.com/
JSONPlaceholder - Free Fake REST API
{JSON} Placeholder Free fake and reliable API for testing and prototyping. Powered by JSON Server + LowDB. Serving ~3 billion requests each month.
jsonplaceholder.typicode.com
package ch02;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class MyHttpAlbumClient {
public static void main(String[] args) {
// 순수 자바코드에서 HTTP 통신
// 1. 서버 주소 경로
// 2. URL 클래스
// 3. url.openConnection() <--- 스트림 I/O
try {
URL url = new URL("https://jsonplaceholder.typicode.com/albums/1");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-type", "application/json");
// 응답 코드 확인
int responseCode = conn.getResponseCode();
System.out.println("response code : " + responseCode);
// HTTP 응답 메세지에 데이터를 추출 [] -- Stream --- []
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer buffer = new StringBuffer();
while( (inputLine = in.readLine()) != null ) {
buffer.append(inputLine);
}
in.close();
System.out.println(buffer.toString());
System.err.println("-------------------------------");
// gson lib 활용
//Gson gson = new Gson();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
Album albumDTO = gson.fromJson(buffer.toString(), Album.class);
System.out.println(albumDTO.getId());
System.out.println(albumDTO.getUserId());
System.out.println(albumDTO.getTitle());
} catch (IOException e) {
e.printStackTrace();
}
} // end of main
}
package ch02;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
/**
* JSON Array 형태를 파싱 해보자.
*/
public class MyHttpAlbumListClient {
public static void main(String[] args) {
// 순수 자바코드에서 HTTP 통신
// 1. 서버 주소 경로
// 2. URL 클래스
// 3. url.openConnection() <--- 스트림 I/O
try {
URL url = new URL("https://jsonplaceholder.typicode.com/albums");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-type", "application/json");
// 응답 코드 확인
int responseCode = conn.getResponseCode();
System.out.println("response code : " + responseCode);
// HTTP 응답 메세지에 데이터를 추출 [] -- Stream --- []
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer buffer = new StringBuffer();
while( (inputLine = in.readLine()) != null ) {
buffer.append(inputLine);
}
in.close();
System.out.println(buffer.toString());
System.err.println("-------------------------------");
// gson lib 활용
//Gson gson = new Gson();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
// 하나의 JSON Object 형태 파싱
// Album albumDTO = gson.fromJson(buffer.toString(), Album.class);
// [{...},{...},{...}]
// Gson 제공하는 Type 이라는 데이터 타입을 활용할 수 있다.
//Json 배열 형태를 쉽게 파싱하는 방법 -> TypeToken 안에 List<T> 을 활용 한다.
Type albumType = new TypeToken<List<Album>>(){}.getType();
List<Album> albumList = gson.fromJson(buffer.toString(), albumType);
System.out.println(albumList.size());
for(Album a : albumList ) {
System.out.println(a.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
} // end of main
}
728x90
반응형
SMALL