- [Java] 111. Json 파싱하기 (2) - (3) Object+Array2024년 06월 07일
- Song hyun
- 작성자
- 2024.06.07.:20
728x90반응형[Java] 111. Json 파싱하기 (2) - (3) Object+Array
1. 단일 Object-Array 파싱하기
2. Object-Array List 파싱하기
1. 단일 Object-Array 파싱하기
https://jsonplaceholder.typicode.com/users/1
위 사이트의 데이터를 파싱해보자.
(1) User
package practice; import javax.imageio.plugins.tiff.GeoTIFFTagSet; import javax.print.attribute.standard.Chromaticity; import com.sun.nio.sctp.PeerAddressChangeNotification.AddressChangeEvent; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Setter @Getter @AllArgsConstructor @NoArgsConstructor public class User { private int id; private String username; private String email; private Address address; private String phone; private String webSite; private Company company; @Override public String toString() { return "User [id=" + id + ", username=" + username + ", email=" + email + ", address=" + address + ", phone=" + phone + ", webSite=" + webSite + ", company=" + company + "]"; } public class Address{ private String streetString; private String suite; private String city; private String zipcode; private Geo geo; @Override public String toString() { return "Address [streetString=" + streetString + ", suite=" + suite + ", city=" + city + ", zipcode=" + zipcode + ", geo=" + geo + "]"; } } public class Geo{ private double lat; private double lng; @Override public String toString() { return "Geo [lat=" + lat + ", lng=" + lng + "]"; } } public class Company{ private String name; private String catchPhrase; private String bs; @Override public String toString() { return "Company [name=" + name + ", catchPhrase=" + catchPhrase + ", bs=" + bs + "]"; } } }
(2) MyHttpUsersClient
package practice; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Type; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; public class MyHttpUsersClient { public static void main(String[] args) { URL url; try { url = new URL("https://jsonplaceholder.typicode.com/users/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); 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.out.println("-----------------------------"); Gson gson=new GsonBuilder().setPrettyPrinting().create(); User userDTO=gson.fromJson(buffer.toString(), User.class); System.out.println(userDTO.getEmail()); System.out.println(userDTO.getPhone()); System.out.println(userDTO.getUsername()); } catch (IOException e) { e.printStackTrace(); } } }
2. Object-Array List 파싱하기
https://jsonplaceholder.typicode.com/users
(1) User class
package practice; import javax.imageio.plugins.tiff.GeoTIFFTagSet; import javax.print.attribute.standard.Chromaticity; import com.sun.nio.sctp.PeerAddressChangeNotification.AddressChangeEvent; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Setter @Getter @AllArgsConstructor @NoArgsConstructor public class User { private int id; private String username; private String email; private Address address; private String phone; private String webSite; private Company company; @Override public String toString() { return "User [id=" + id + ", username=" + username + ", email=" + email + ", address=" + address + ", phone=" + phone + ", webSite=" + webSite + ", company=" + company + "]"; } public class Address{ private String streetString; private String suite; private String city; private String zipcode; private Geo geo; @Override public String toString() { return "Address [streetString=" + streetString + ", suite=" + suite + ", city=" + city + ", zipcode=" + zipcode + ", geo=" + geo + "]"; } } public class Geo{ private double lat; private double lng; @Override public String toString() { return "Geo [lat=" + lat + ", lng=" + lng + "]"; } } public class Company{ private String name; private String catchPhrase; private String bs; @Override public String toString() { return "Company [name=" + name + ", catchPhrase=" + catchPhrase + ", bs=" + bs + "]"; } } }
(2) MyHttpUsersClient
package practice; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Type; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; public class MyHttpUsersClient2 { public static void main(String[] args) { URL url; try { url = new URL("https://jsonplaceholder.typicode.com/users"); HttpURLConnection conn=(HttpURLConnection)url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Content-type", "application/json"); int responseCode=conn.getResponseCode(); System.out.println("response code : "+responseCode); 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("-----------------------------"); Gson gson=new GsonBuilder().setPrettyPrinting().create(); Type userType=new TypeToken<List<User>>() {}.getType(); List<User> userList=gson.fromJson(buffer.toString(),userType); System.out.println(userList.size()); for(User u:userList) { System.out.println(u.toString()); System.out.println(); } } catch (IOException e) { e.printStackTrace(); } } }
728x90반응형'Java > 네트워크 통신' 카테고리의 다른 글
[Java] 113. JDBC 사용법 (0) 2024.06.11 [Java] 112. MySQL 쿼리 파싱하기 (0) 2024.06.10 [Java] 110. JSON 파싱 연습 (2) - (2) Array (0) 2024.06.07 [Java] 109. JSON 파싱 연습 (2) - (1) Object (0) 2024.06.07 [Java] 108. jsonPlaceHolder 파싱하기 (0) 2024.06.05 다음글이전글이전 글이 없습니다.댓글
스킨 업데이트 안내
현재 이용하고 계신 스킨의 버전보다 더 높은 최신 버전이 감지 되었습니다. 최신버전 스킨 파일을 다운로드 받을 수 있는 페이지로 이동하시겠습니까?
("아니오" 를 선택할 시 30일 동안 최신 버전이 감지되어도 모달 창이 표시되지 않습니다.)