반응형

# JSON API 활용 (Gson)

  • 오픈 API, 공공 API 등에서 클라이언트에게 전달하는 자료 형태가 JSON인 경우가 대부분임.

## Gson API 다운로드 및 적용방법. (mvnrepository, Build Path)

 

Maven Repository: Gson

Feign Gson Last Release on Dec 23, 2021

mvnrepository.com

  1. jar 파일로 API 다운로드 받은 경우 lib 폴더 등에 jar 파일 저장.
  2. 프로젝트 우 클릭 Build Path > configure Build Path 클릭.
  3. Libraries > Add External JARs 클릭하여 저장한 jar 파일 추가. (자바가 12버전 이상인 경우 Modulepath(자바모듈) 와 Classpath(외부 API 모듈)로 나누어 표시(관리)되어 있어서 Classpath에 추가해주면 되는데, 자바가 그 이전 버전인 경우에는 Add ExternalJARs 해서 바로 추가해주면 됨) 
  4. 완료 후 아래와 같이 Referenced Libraries에 해당 API가 추가되어있는지 확인, 사용 시에는 import 하여 사용하면 된다.

## Gson API 사용.

  • 아래와 같이 import 하여 사용 가능.
import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import kr.inflearn.BookDTO;

public class Project01_A {
	public static void main(String[] args) {
		// 1. 객체 -> 문자열 (Object(BookDTO) -> JSON(String))
		BookDTO book = new BookDTO("갓바", 250000, "출판사A", 300);
		
		Gson g = new Gson();
		String json = g.toJson(book);
		System.out.println(json);	// {"title":"갓바","price":250000,"company":"출판사A","page":300}

		// 2. 문자열 -> 객체 (JSON(String) -> Object(BookDTO))
		BookDTO book1 = g.fromJson(json, BookDTO.class);
		System.out.println(book1);	// BookDTO [title=갓바, price=250000, company=출판사A, page=300]
		System.out.println(book1.getTitle() + "\t" + book1.getPrice() + "\t" + book1.getCompany() + "\t" + book1.getPage());	// 갓바	250000	출판사A	300
		
		// 3. Object(List<BookDTO>) -> JSON(String) : [{ }, { }, ...] 형태.
		List<BookDTO> list = new ArrayList<BookDTO>();
		list.add(new BookDTO("갓바", 250000, "출판사A", 300));
		list.add(new BookDTO("파이썬", 50000, "출판사B", 150));
		list.add(new BookDTO("노드", 100000, "출판사C", 400));
		
		String listJson = g.toJson(list);
		System.out.println(listJson);	// [{"title":"갓바","price":250000,"company":"출판사A","page":300},{"title":"파이썬","price":50000,"company":"출판사B","page":150},{"title":"노드","price":100000,"company":"출판사C","page":400}]
		
		// 4. JSON(String) -> Object(List<BookDTO>)
		List<BookDTO> list2 = g.fromJson(listJson, new TypeToken<List<BookDTO>>(){}.getType());
		for(BookDTO vo : list2) {
			System.out.println(vo.toString());
			// BookDTO [title=갓바, price=250000, company=출판사A, page=300]
			// BookDTO [title=파이썬, price=50000, company=출판사B, page=150]
			// BookDTO [title=노드, price=100000, company=출판사C, page=400]
		}
		
	}
}

 

 

# JSON API 활용 (JSON-Java(org.json))

## JSONObject, JSONArray

  • JSONObject : {  } 형태, 하나의 객체를 표현. (key : value)
{
	"address" : "대전",
	"phone" : "010-1234-1234",
	"name" : "둘리"
}
  • JSONArray : [  ] 형태
[
	{
		"address" : "대전",
		"phone" : "010-1234-1234",
		"name" : "둘리"
	} ,
	{
		"address" : "세종",
		"phone" : "010-4321-4321",
		"name" : "뽀로로"
	}
]
  • 아래와 같이 JSONObject로 표현 가능.
{ "students" : [
	{
		"address" : "대전",
		"phone" : "010-1234-1234",
		"name" : "둘리"
	} ,
	{
		"address" : "세종",
		"phone" : "010-4321-4321",
		"name" : "뽀로로"
	}
] }
  • JSONObject 아래와 같이 사용 가능.
JSONObject student = new JSONObject();
student.put("name", "강아지");
student.put("address", "청주");
student.put("phone", "010-1234-1234");


// key를 이용해서 출력 가능.
System.out.println(student.get("name"));
System.out.println(student.get("address"));
System.out.println(student.get("phone"));

## JSON Data 분석

 

JSON Editor Online: JSON editor, JSON formatter, query JSON

You need to enable JavaScript to run this app. News Export to CSV 2022-06-07 A useful new feature: you can now export your JSON to CSV via menu "Save", "Export to CSV". A typical use case is to load your JSON data into JSON Editor Online and preprocess it

jsoneditoronline.org

반응형

+ Recent posts