본문 바로가기
JAVA

[JAVA] Gson JsonParser

by 김뚱 2020. 2. 25.

구글에서 만든 Json Mapper 이다. gson은 maven저장소를 지원한다.

 

1.pom.xml 설정

<dependency>
	<groupId>com.google.code.gson</groupId>
	 <artifactId>gson</artifactId>
	 <version>2.8.5</version>
</dependency>

 

2.객체를 JSON으로 변경

2-1) Gson gson = new Gson(); 

2-2) String json = gson.toJson(객체); 

 

3.JSON을 객체로 변경

3-1)Test test = gson.fromJson(json, Test.class); 

- 첫번째 : 문자열, 두번째 : 매핑할 클래스

 

4.JSON 만들기

4-1)JsonObject object = new JsonObject object();

4-2)object.addProperty("key", "value");

 

5.json 파싱

5-1)JsonParser parser = new JsonParser();

5-2)String json = gson.toJson(객체);

5-3)JsonElement element = parser.parse(json);

5-4)JsonObject object = element.getAsJsonObject();

5-5)JsonArray array = object.get("key").getAsJsonArray(); (object 안에 json array 가 존재하는 경우)

 

*추가*

<Json에서 특정 key의 value만 가져오는 경우>

String info = element.getAsJsonObject().get("key").getAsString();

 

Refference

https://nesoy.github.io/articles/2018-04/Java-JSON

 

Java JSON 라이브러리에 대해

 

nesoy.github.io

https://www.developer.com/lang/jscript/top-7-open-source-json-binding-providers-available-today.html

 

Top 7 Open-Source JSON-Binding Providers Available Today - Developer.com

Top 7 Open-Source JSON-Binding Providers Available Today --> Introduction (Business Case)             JSON, acronym for JavaScript Object Notation, is a lightweight data-interchange format, an alternative to XML, but smaller, faster and easier to parse. Be

www.developer.com

https://howtodoinjava.com/gson/gson-jsonparser/

 

Gson JsonParser - Parse JSON String to JsonElement - HowToDoInJava

Gson JsonParser is used to parse Json data into a parse tree of JsonElement and thus JsonObject, which can be used to get JSON values using their keys.

howtodoinjava.com

 

728x90
반응형

'JAVA' 카테고리의 다른 글

[JAVA] Reflection 개념  (0) 2019.05.22

댓글