티스토리 뷰
JSON
REST API 1
REST?
REST 구체적 개념
REST 장단점
REST 필요 이유
REST 구성 요소
REST API란
RESTful?
REST API 2 ( 데이터 표현형식)
BookDTO.java
package com.vcx.dd;
public class BookDTO {
private String title;
private int price;
private String company;
private int page;
public BookDTO() {
super();
// TODO Auto-generated constructor stub
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
@Override
public String toString() {
return "BookDTO [title=" + title + ", price=" + price + ", company=" + company + ", page=" + page + "]";
}
public BookDTO(String title, int price, String company, int page) {
super();
this.title = title;
this.price = price;
this.company = company;
this.page = page;
}
}
Project01.java
package com.vcx.dd;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class Project01 {
public static void main(String[] args)
{
//1.Object(BookDTO) -> JSON(String) : 객체를 JSON으로 변한하기
BookDTO dto = new BookDTO("자바", 21000, "에이콘", 670);
Gson g = new Gson();
String json = g.toJson(dto);
System.out.println(json);
//{"title" : "자바", "price" : 21000, "company":"에이콘", "page":670}
//2.JSON(String) -> Object(BookDTO) : JSON을 객체로 변환하기
BookDTO dtol = g.fromJson(json, BookDTO.class);
System.out.println(dtol);
//BookDTO [title=자바, price=21000, company=에이콘, page=670]
System.out.println(dtol.getTitle()+"\t"+dtol.getPrice());
//3.Object(List<BookDTO>) -> JSON(String) : [{},{}...] 배열을 JSON으로 바꾸기
List<BookDTO> lst = new ArrayList<BookDTO>();
lst.add(new BookDTO("자바1", 21000, "에이콘1", 570));
lst.add(new BookDTO("자바2", 31000, "에이콘2", 670));
lst.add(new BookDTO("자바3", 11000, "에이콘3", 370));
String lstJson = g.toJson(lst);
System.out.println(lstJson);
//4.JSON(String) -> Object(List<BookDTO>)
List<BookDTO> lstl = g.fromJson(lstJson, new TypeToken<List<BookDTO>>() {}.getType());
for(BookDTO vo : lstl)
{
System.out.println(vo);
}
}
}
console
JSON API 활용
1.step1
//json object 만들기
JSONObject student1 = new JSONObject();
JSONObject student2 = new JSONObject();
student1.put("name", "홍길동");
student1.put("phone", "010-1111-1111");
student1.put("address", "서울");
student2.put("name", "나길동");
student2.put("phone", "010-2222-2222");
student2.put("address", "광주");
System.out.println(student1);
System.out.println(student2);
2.step2
//배열에 넣어주기(ArrayList)
JSONArray students = new JSONArray();
students.put(student1);
students.put(student2);
3.step3
//Object로 만들어주기
JSONObject object = new JSONObject();
object.put("students", students);
System.out.println(object.toString(2));
result
info.json
Project03.java
package com.json.dd;
import java.io.InputStream;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
public class Project03 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String src = "info.json";
InputStream is = Project03.class.getResourceAsStream(src);
if(is==null)
{
throw new NullPointerException("파일이 존재하지 않습니다.");
}
JSONTokener tokener = new JSONTokener(is);
JSONObject object = new JSONObject(tokener);
JSONArray students = object.getJSONArray("students");
for(int i = 0; i<students.length(); i++)
{
JSONObject student = (JSONObject)students.get(i);
System.out.println(student.get("name")+"\t");
System.out.println(student.get("address")+"\t");
System.out.println(student.get("phone"));
}
}
}
Console
위도와 경도 위치
1번.
2번
package com.vcx.dd;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
public class Project04 {
public static void map_service(String point_x, String point_y, String address)
{
String URL_STATICMAP = "https://naveropenapi.apigw.ntruss.com/map-static/v2/raster?";
try {
//네이버 전달 url 생성 // 위도와 경도를 변수처리한다.
String pos = URLEncoder.encode(point_x + " " + point_y,"UTF-8");
String url = URL_STATICMAP;
url += "center=" + point_x + "," + point_y;
url += "&level=16&w=700&h=500";
url += "&markers=type:t|size:mid|pos:" +pos+"|label:"+URLEncoder.encode(address,"UTF-8");
URL u = new URL(url);
HttpURLConnection con = (HttpURLConnection)u.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("X-NCP-APIGW-API-KEY-ID", "1w1vepnes5");
con.setRequestProperty("X-NCP-APIGW-API-KEY", "XfI1h7i9AZFuNWv5GjeTIuWzzKD3WjH6XjM1bLjM");
int responseCode = con.getResponseCode();
BufferedReader br;
if(responseCode == 200)
{
InputStream is = con.getInputStream();
int read = 0;
byte[] bytes = new byte[1024];
String tempname = Long.valueOf(new Date().getTime()).toString();
File f = new File(tempname + ".jpg");
f.createNewFile();
OutputStream outputStream = new FileOutputStream(f);
while ((read = is.read(bytes)) != -1)
{
outputStream.write(bytes, 0 , read);
}
is.close();
}
else
{
br = new BufferedReader(new InputStreamReader(con.getErrorStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while((inputLine = br.readLine())!=null)
{
response.append(inputLine);
}
br.close();
System.out.println(response.toString());
}
}
catch (Exception e) {
// TODO Auto-generated catch block
System.out.println(e);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String client_id = "1w1vepnes5";
String client_secret = "XfI1h7i9AZFuNWv5GjeTIuWzzKD3WjH6XjM1bLjM";
BufferedReader io = new BufferedReader(new InputStreamReader(System.in));
try
{
System.out.println("주소를 입력하세요");
String address=io.readLine();
String addr=URLEncoder.encode(address, "UTF-8");
String reqUrl = "https://naveropenapi.apigw.ntruss.com/map-geocode/v2/geocode?query="+addr;
URL url = new URL(reqUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("X-NCP-APIGW-API-KEY-ID",client_id );
con.setRequestProperty("X-NCP-APIGW-API-KEY", client_secret);
BufferedReader br;
int responseCode = con.getResponseCode();
if(responseCode == 200)
{
br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
}
else
{
br = new BufferedReader(new InputStreamReader(con.getErrorStream()));
}
//임시저장소
String line;
//StringBuffer 사용하는 이유는 String으로 사용한다면 기존껄 놔두고 새로 생성.
//StringBuffer는 기존꺼에 계속 더해져서 만들어가기때문에 용량 공간낭비를 하지 않는다.
StringBuffer response = new StringBuffer();
while((line=br.readLine())!= null)
{
response.append(line);
}
br.close();
//json을 문자열로 생성
JSONTokener tokener = new JSONTokener(response.toString());
JSONObject object = new JSONObject(tokener);
System.out.println(object.toString());
String x = null;
String y = null;
String z = null;
JSONArray arr=object.getJSONArray("addresses");
for(int i=0; i<arr.length(); i++)
{
JSONObject temp = (JSONObject) arr.get(i);
System.out.println("address :" + temp.get("roadAddress"));
System.out.println("jibunAddress :" + temp.get("jibunAddress"));
System.out.println("경도 :" + temp.get("x"));
System.out.println("위도 :" + temp.get("y"));
x = (String) temp.get("x");
y = (String) temp.get("y");
z = (String) temp.get("roadAddress");
}
map_service(x,y,z);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
NAVER CLOUD PLATFORM
cloud computing services for corporations, IaaS, PaaS, SaaS, with Global region and Security Technology Certification
www.ncloud.com
참고 사이트 : JSON Viewer [ https://codebeautify.org/jsonviewer ]
Best JSON Viewer and JSON Beautifier Online
Online JSON Viewer, JSON Beautifier and Formatter to beautify and tree view of JSON data - It works as JSON Pretty Print to pretty print JSON data.
codebeautify.org
'정리 노트 > Spring' 카테고리의 다른 글
Spring[17-4] (0) | 2024.02.01 |
---|---|
Spring Chapter14-Chapter15 [17-3] (0) | 2024.01.31 |
Spring Chapter13~Chapter14 [17-1] (0) | 2024.01.29 |
Spring이 사용하는 객체&어노테이션 Chapter 총 정리 (0) | 2024.01.26 |
Spring Chapter13 [16-5] (0) | 2024.01.26 |