Android Google Gson 예제 및 자습서.
Gson(Google Gson이라고도 함)은 JSON 개체를 구문 분석하고 생성하기 위한 작은 Java 기반 라이브러리입니다.
Java 객체를 JSON으로 변환하고 그 반대로 변환하는 직렬화/역직렬화 라이브러리입니다.
Google은 자체 프로젝트를 위해 Gson을 개발했지만 나중에 버전 1.0부터 Gson을 공개적으로 사용할 수 있게 했습니다.
Gson은 매우 강력하며 소스 코드가 없는 기존 객체를 포함하여 임의의 Java 객체로 작업할 수 있습니다.
Gson의 용도
- Java 객체를 JSON으로 변환하고 그 반대로.
- JSON 문자열을 동등한 Java 객체로 변환.
지손이 만들어진 이유
Gson을 만든 이유는 다음과 같습니다.
- 간단한
toJson()
및fromJson()
메소드를 제공하여 JSON 작업을 쉽게 합니다. 이러한 방법을 사용하면 Java 개체를 JSON으로 또는 그 반대로 변환할 수 있습니다. - 기존의 수정 불가능한 객체를 JSON으로 변환하거나 JSON에서 변환할 수 있도록 합니다.
- Java Generics의 광범위한 지원을 제공합니다.
- 개체에 대한 사용자 지정 표현을 허용하려면
- 임의의 복잡한 객체에 대한 지원 제공(깊은 상속 계층 및 일반 유형의 광범위한 사용)
Gson 설치
Gson은 Android를 포함한 Java 기반 프로젝트를 대상으로 합니다. 즉, 빌드 시스템에 따라 최소한 여러 가지 설치 방법이 있습니다.
(a) Gradle
예를 들어 Android를 사용하는 경우 Android Studio와 Gradle을 사용하고 있을 가능성이 큽니다.
이 경우 앱 수준 build.gradle의 종속성에 다음을 추가합니다.
implementation 'com.google.code.gson:gson:2.8.5'
(b) 메이븐
일반 Java 프로젝트를 생성하는 경우 Maven을 사용할 가능성이 큽니다.
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
(c) 항아리
jar를 직접 사용하는 마지막 옵션입니다. Maven Central에서 다운로드하여 프로젝트에 추가합니다.
여기에서 Jar를 다운로드합니다.
중요 수업
(a) 지손
Gson
은 com.google.gson
패키지에 있는 클래스로 Gson 라이브러리를 사용하기 위해 필요한 기본 클래스입니다.
일반적으로 우리는 먼저 Gson 인스턴스를 생성한 다음 toJson(Object)
또는 fromJson(String, Class)
메소드를 호출하여 이를 사용합니다.
(b). JsonElement
JsonElement
는 Json의 요소를 나타내는 com.google.gson
패키지에 있는 클래스입니다.
다음은 JsonElement 객체입니다.
- '제이슨오브젝트'
제이슨어레이
- '제이슨프리미티브'
- 'JsonNull'.
(c) JsonObject
JsonObject
는 Json의 객체 유형을 나타내는 com.google.gson
패키지에 있는 클래스입니다.
이 객체는 이름이 문자열이고 값이 'JsonElement'의 다른 유형인 이름-값 쌍으로 구성될 수 있습니다.
이를 통해 JsonElements 트리를 구축할 수 있습니다. 이러한 요소는 추가된 순서대로 유지됩니다.
(d) JsonParser
JsonParser
는 Json을 JsonElements의 구문 분석 트리로 구문 분석하는 데 사용되는 com.google.gson
패키지에 있는 클래스입니다.
Gson 만들기
1. 지손()
Gson 객체를 생성하거나 생성하는 첫 번째 방법은 기본 생성자 Gson()
을 사용하는 것입니다.
이것은 기본 구성으로 Gson 객체를 생성합니다.
해당 기본 구성에는 다음 설정이 있습니다.
- toJson 메소드에 의해 생성된 JSON은 간결하게 표현됩니다. 즉, 불필요한 공백이 모두 제거됩니다. 이 동작은
GsonBuilder#setPrettyPrinting()
으로 변경할 수 있습니다. - 생성된 JSON은 null인 모든 필드를 생략합니다. 배열은 순서가 지정된 목록이므로 배열의 null은 그대로 유지됩니다. 또한 필드가 null이 아니지만 생성된 JSON이 비어 있으면 필드가 유지됩니다. GsonBuilder#serializeNulls()를 설정하여 null 값을 직렬화하도록 Gson을 구성할 수 있습니다.
- Gson은 Enums, Map, java.net.URL, java.net.URI, java.util.Locale, java.util.Date, java.math.BigDecimal 및 java.math.BigInteger 클래스에 대한 기본 직렬화 및 역직렬화를 제공합니다. .
2. 지손빌더
'GsonBuilder'는 다양한 구성 설정으로 Gson을 인스턴스화하는 데 사용할 수 있습니다.
Gson gson = new GsonBuilder().setPrettyPrinting().create();
GsonBuilder는 빌더 패턴을 따르며 일반적으로 원하는 옵션을 설정하기 위해 다양한 구성 메소드를 먼저 호출하고 마지막으로 create()
메소드를 호출하여 사용합니다.
중요한 Gson 메소드
(ㅏ). toJson()
이 메서드는 제네릭 형식을 포함하여 지정된 개체를 해당 Json 표현으로 직렬화합니다.
Gson gson = new Gson();
gson.toJson(map);
지정된 개체가 제네릭 형식인 경우 사용해야 합니다. 제네릭이 아닌 객체의 경우 대신 toJson(Object,Appendable)
을 사용하세요.
(비). fromJson
이 메소드는 지정된 Json을 지정된 유형의 객체로 역직렬화합니다. 이 메서드는 지정된 개체가 제네릭 형식인 경우에 유용합니다. 제네릭이 아닌 객체의 경우 fromJson(String,Class)
을 대신 사용하세요.
String 대신 Reader에 Json이 있는 경우 대신 fromJson(Reader,Type)
을 사용하십시오.
(씨). toJsonTree
이 메소드는 제네릭 유형의 객체를 포함하여 지정된 객체를 JsonElements의 트리와 동일한 표현으로 직렬화합니다. 지정된 개체가 제네릭 형식인 경우 이 메서드를 사용해야 합니다. 일반 객체가 아닌 경우 toJsonTree(Object)
를 대신 사용하세요.
(디). getAdapter
유형에 대한 유형 어댑터를 반환합니다.
전체 Gson Hello World 예제
전체 Gson hello world 예제를 살펴보겠습니다. Gson을 설치하고 실행하기만 하면 이 예제를 IDE에 복사하여 붙여넣을 수 있습니다.
import com.google.gson.Gson;
/**
* Gson Hello World
*
*/
public class GsonHelloWorld {
public static void main(String[] args) {
// init class
Place place = new Place();
place.setName("World");
Human human = new Human();
human.setMessage("Hi");
human.setPlace(place);
// convert to json
Gson gson = new Gson();
String jsonString = gson.toJson(human);
System.out.println("json " + jsonString); // print "json {"message":"Hi","place":{"name":"World"}}"
// convert from json
Human newHuman = gson.fromJson(jsonString, Human.class);
newHuman.say(); // print "Hi , World!"
}
private static class Human {
private String message;
private Place place;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Place getPlace() {
return place;
}
public void setPlace(Place place) {
this.place = place;
}
public void say() {
System.out.println();
System.out.println(getMessage() + " , " + getPlace().getName() + "!");
}
}
private static class Place {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
빠른 GSON 예제 및 방법
이 예에서는 Google Gson을 사용하고 있습니다.
1. 지도를 JSON으로 변환하는 방법
'String' 키와 'T' 값이 있는 지도를 제공한다고 가정해 보겠습니다. 그리고 매핑하거나 JSON 문자열로 변환하라고 합니다.
어떻게 하시겠습니까?
글쎄, 당신은 단순히 Gson
클래스의 toJson()
메소드를 사용할 수 있습니다. 먼저 'Gson' 클래스를 인스턴스화한 다음 해당 메서드를 호출해야 합니다.
public static <T> String mapToJsonStr(Map<String, T> map) {
Gson gson = new Gson();
return gson.toJson(map);
}
2. JSON을 지도로 변환하는 방법
JSON 문자열이 있고 Java에서 'Map' 데이터 구조로 변환하도록 요청하는 경우는 어떻습니까?
그렇다면 Gson
의 fromJson()
메소드를 사용합니다.
그러나 이번에는 'Map'을 일반 매개변수로 사용하여 'TypeToken'을 인스턴스화해야 합니다. 그런 다음 fromJson()
메소드의 첫 번째 매개변수로 json 문자열을 전달합니다. 그리고 'Type' 인스턴스를 두 번째 매개변수로 사용합니다.
public static <T> Map<String, T> jsonStrToMap(String jsonStr) {
Gson gson = new Gson();
Type type = new TypeToken<Map<String, T>>() {
}.getType();
return gson.fromJson(jsonStr, type);
}
삼. JSON을 객체로 변환하는 방법
좋습니다. JSON 문자열이 있고 이를 주어진 유형의 객체로 변환하라는 메시지가 표시됩니다.
음, 다시 json 문자열과 유형을 fromJson()
메서드에 전달합니다.
public static <T> T jsonToObj(String jsonStr, Class<T> classOfT) {
return new Gson().fromJson(jsonStr, classOfT);
}
4. JSON을 ArrayList로 변환하는 방법
많은 프로젝트에서 일반적인 시나리오는 json 문자열을 가장 일반적으로 사용되는 컬렉션인 ArrayList로 변환하는 것입니다.
빈 값을 확인하기 위해 TextUtils
' isEmpty()
메서드를 사용하여 시작합니다.
그런 다음 일반 유형으로 전달된 JSONObject의 ArrayList
를 사용하여 TypeToken
인스턴스를 얻습니다.
그런 다음 fromJson()
메서드를 사용하여 JSONObject의 ArrayList를 가져옵니다.
그런 다음 이제 루프를 통해 채우고 채우려는 ArrayList를 채울 수 있습니다.
public static <T> ArrayList<T> jsonToArrayList(String json, Class<T> clazz) {
if (TextUtils.isEmpty(json)) {
return null;
}
Type type = new TypeToken<ArrayList<JsonObject>>() {
}.getType();
ArrayList<JsonObject> jsonObjects = new Gson().fromJson(json, type);
ArrayList<T> arrayList = new ArrayList<>();
for (JsonObject jsonObject : jsonObjects) {
arrayList.add(new Gson().fromJson(jsonObject, clazz));
}
return arrayList;
}
5. 목록을 JSON으로 변환하는 방법
또 다른 일반적인 것은 List를 json 문자열로 변환하는 것입니다. 아마도 당신은 그 목록을 직렬화하고 그것을 API로 노출시키는 위치나 기본적인 방법을 통해 그것을 보내고 싶을 것입니다.
다시 말하지만, toJson()
메소드는 우리를 위해 그것을 쉽게 합니다.
public static <T> String listToJson(List<T> list) {
Gson gson = new Gson();
String jsonstring = gson.toJson(list);
return jsonstring;
}
6. 객체를 JSON으로 변환하는 방법
객체가 있고 이를 JSON으로 변환해야 합니다. 매개변수로 전달된 객체를 사용하여 toJson()
메서드를 호출하기만 하면 됩니다.
public static <T> String object2Json(T t) {
Gson gson = new Gson();
return gson.toJson(t);
}
7. 주석 없이 직렬화에서 특정 필드를 제외하는 방법
일반적으로 Gson의 주석을 통해 포함할 필드를 제어합니다. 그러나 주석 없이도 수행할 수 있습니다.
Gson gson = new GsonBuilder()
.setExclusionStrategies(new TestExclStrat())
//.serializeNulls() <-- uncomment to serialize NULL fields as well
.create();
Student src = new Student();
String json = gson.toJson(src);
System.out.println(json);
8. Gson으로 예쁘게 인쇄하는 방법
PrettyPrinting은 JSON 데이터를 더 읽기 쉽게 만들기 위해 공백을 추가하는 것을 의미합니다. GsonBuilder#setPrettyPrinting()
을 사용할 수 있습니다.
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(uglyJSONString);
String prettyJsonString = gson.toJson(je);
9. TreeModel을 사용하여 JSON을 작성하는 방법
여기 중요한 방법이 있습니다. json 데이터를 읽고 쓰는 두 가지 방법이 있습니다.
전체 수업은 다음과 같습니다.
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
public class TreeModel {
public static void main(String[] args) throws IOException {
System.out.print("readJson: ");
readJson();
System.out.println();
System.out.print("writeJson: ");
writeJson();
}
/**
* Example to readJson using TreeModel
*/
private static void readJson() throws IOException {
JsonParser parser = new JsonParser();
JsonElement jsonElement = parser.parse("{"message":"Hi","place":{"name":"World!"}}");
JsonObject rootObject = jsonElement.getAsJsonObject();
String message = rootObject.get("message").getAsString(); // get property "message"
JsonObject childObject = rootObject.getAsJsonObject("place"); // get place object
String place = childObject.get("name").getAsString(); // get property "name"
System.out.println(message + " " + place); // print "Hi World!"*/
}
/**
* Example to writeJson using TreeModel
*/
private static void writeJson() throws IOException {
JsonObject rootObject = new JsonObject();
rootObject.addProperty("message", "Hi");
JsonObject childObject = new JsonObject();
childObject.addProperty("name", "World!");
rootObject.add("place", childObject);
Gson gson = new Gson();
String json = gson.toJson(rootObject);
System.out.println(json); // print "{"message":"Hi","place":{"name":"World!"}}"
}
}
10. 문자열을 객체로 변환하는 방법
Gson myGson = new GsonBuilder().setPrettyPrinting().create();
myGson.fromJson(jsonString, Person.class)
11. 예쁜 인쇄 JSON 문자열
private static String pretty(String json) {
JsonElement gson = new JsonParser().parse(json);
return new GsonBuilder().setPrettyPrinting().serializeNulls().create().toJson(gson);
}
}
12. Gson을 사용한 스트리밍 API 읽기 및 쓰기
JSON Streaming API 읽기 및 쓰기 예제입니다. JsonReader, JsonToken 및 JsonWriter 클래스를 사용합니다.
우리는 main()
메소드, readJSON()
메소드 및 writeJson()
메소드의 세 가지 메소드가 있습니다.
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import java.io.*;
import java.nio.charset.Charset;
public class StreamingAPI {
public static void main(String[] args) throws IOException {
System.out.print("readJson: ");
readJson();
System.out.println();
System.out.print("writeJson: ");
writeJson();
}
/**
* Example to readJson using StreamingAPI
*/
private static void readJson() throws IOException {
String str = "{"message":"Hi","place":{"name":"World!"}}";
InputStream in = new ByteArrayInputStream(str.getBytes(Charset.forName("UTF-8")));
JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
while (reader.hasNext()) {
JsonToken jsonToken = reader.peek();
if(jsonToken == JsonToken.BEGIN_OBJECT) {
reader.beginObject();
} else if(jsonToken == JsonToken.END_OBJECT) {
reader.endObject();
} if(jsonToken == JsonToken.STRING) {
System.out.print(reader.nextString() + " "); // print Hi World!
} else {
reader.skipValue();
}
}
reader.close();
}
/**
* Example to writeJson using StreamingAPI
*/
private static void writeJson() throws IOException {
OutputStream outputStream = new ByteArrayOutputStream();
JsonWriter writer = new JsonWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.beginObject(); // main object
writer.name("message");
writer.value("Hi");
writer.name("place"); // save object Place
writer.beginObject();
writer.name("name");
writer.value("World!");
writer.endObject();
writer.endObject();
writer.close();
System.out.println(outputStream.toString()); // print "{"message":"Hi","place":{"name":"World!"}}"
}
}
13. 전체 재사용 가능한 Gson 유틸리티 클래스
ublic class GsonUtils {
privatestaticfinaldoubleVERSION=1.0f;
private static final Gson sGson = createGson(true, false);
private static final Gson sGsonExpose = createGson(true, true);
private GsonUtils () {
thrownewAssertionError();
}
/**
* Create the standard {@link Gson} configuration
*
* @return created gson, never null
*/
public static Gson createGson() {
return createGson(true, false);
}
/**
* Create the standard {@link Gson} configuration
*
* @param serializeNulls whether nulls should be serialized
* @return created gson, never null
*/
private static Gson createGson(final boolean serializeNulls,
final boolean exposeEnable ) {
final GsonBuilder builder = new GsonBuilder ();
if (serializeNulls) {
builder.serializeNulls();
}
builder . setVersion ( VERSION );
// json format
// builder.setPrettyPrinting();
if (exposeEnable) {
builder.excludeFieldsWithoutExposeAnnotation();
}
return builder.create();
}
/**
* Get reusable pre-configured {@link Gson} instance
*
* @return Gson instance
*/
public static Gson getGson() {
return sGson;
}
/**
* Get reusable pre-configured {@link Gson} instance
*
* @return Gson instance
*/
public static Gson getGson(final boolean exposeEnable) {
return exposeEnable ? sGsonExpose : sGson;
}
/**
* Convert object to json, only exports attributes that have been annotated with @Expose
*
* @param object
* @return json string
*/
public static String toJson(final Object object) {
return toJson(object, true);
}
/**
* Convert object to json
*
* @param object
* @param exposeEnable Whether to export only @Expose annotated properties, true is only exported by @Expose
* @return json string
*/
public static String toJson(final Object object,
final boolean exposeEnable ) {
return exposeEnable ? sGsonExpose.toJson(object) : sGson.toJson(object);
}
/**
* Convert string to given type
*
* @param json
* @param type
* @return instance of type
*/
public static <V> V fromJson(String json, Class<V> type) {
return sGson.fromJson(json, type);
}
/**
* Convert string to given type
*
* @param json
* @param type
* @return instance of type
*/
public static <V> V fromJson(String json, Type type) {
returnsGson.fromJson(json,type);
}
/**
* Convert content of reader to given type
*
* @param reader
* @param type
* @return instance of type
*/
public static <V> V fromJson(Reader reader, Class<V> type) {
return sGson.fromJson(reader, type);
}
/**
* Convert content of reader to given type
*
* @param reader
* @param type
* @return instance of type
*/
public static <V> V fromJson(Reader reader, Type type) {
returnsGson.fromJson(reader,type);
}
/**
* Convert object object to map only supports basic types
*
* @param src
* @param exposeEnable
* @return
*/
public static HashMap<String, String> toMap(Object src, boolean exposeEnable) {
Gson gson = exposeEnable ? sGsonExpose : sGson;
HashMap<String, String> params = new HashMap<String, String>();
try {
if (src == null) {
return null;
}
JsonElement jsonTree = gson . toJsonTree ( src );
JsonObject jsonObj = jsonTree.getAsJsonObject();
Iterator<Entry<String, JsonElement>> iterator = jsonObj.entrySet().iterator();
String curKey;
JsonElement curVal ;
while (iterator.hasNext()) {
Entry<String, JsonElement> entry = iterator.next();
curKey = entry.getKey();
curVal = entry.getValue();
if (!curVal.isJsonNull()) {
params.put(curKey, curVal.getAsString());
}
}
return params;
} Catch ( Exception e ) {
e . printStackTrace ();
}
returnparams;
}
public static <T> String mapToJson(Map<String, T> map) {
Gson gson = new Gson ();
return gson . toJson (folder);
}
}