在本文中,我們將探討使用 Gson 庫 的最常見場景。
讓我們首先介紹一個我們將會在後續示例中使用的一個 簡單實體:
public class SourceClass {
private int intValue;
private String stringValue;
// standard getters and setters
}1. 序列化實體數組
首先,我們使用 Gson 序列化一個對象數組:
@Test
public void givenArrayOfObjects_whenSerializing_thenCorrect() {
SourceClass[] sourceArray = {new SourceClass(1, "one"), new SourceClass(2, "two")};
String jsonString = new Gson().toJson(sourceArray);
String expectedResult =
"[{"intValue":1,"stringValue":"one"},{"intValue":2,"stringValue":"two"}]";
assertEquals(expectedResult, jsonString);
}2. 序列化實體集合
接下來,我們同樣對實體集合執行相同的操作:
@Test
public void givenCollection_whenSerializing_thenCorrect() {
Collection<SourceClass> sourceCollection =
Lists.newArrayList(new SourceClass(1, "one"), new SourceClass(2, "two"));
String jsonCollection = new Gson().toJson(sourceCollection);
String expectedResult =
"[{"intValue":1,"stringValue":"one"},{"intValue":2,"stringValue":"two"}]";
assertEquals(expectedResult, jsonCollection);
}3. 修改實體序列化時的字段名稱
接下來,讓我們看看如何在序列化實體時更改字段名稱。
我們將序列化我們的實體,該實體包含intValue和stringValue字段,將其轉換為包含otherIntValue和otherStringValue的JSON。
@Test
public void givenUsingCustomSerializer_whenChangingNameOfFieldOnSerializing_thenCorrect() {
SourceClass sourceObject = new SourceClass(7, "seven");
GsonBuilder gsonBuildr = new GsonBuilder();
gsonBuildr.registerTypeAdapter(SourceClass.class, new DifferentNameSerializer());
String jsonString = gsonBuildr.create().toJson(sourceObject);
String expectedResult = "{"otherIntValue":7,"otherStringValue":"seven"}";
assertEquals(expectedResult, jsonString);
}請注意,我們在這裏使用自定義序列化器來更改字段的名稱:
public class DifferentNameSerializer implements JsonSerializer<SourceClass> {
@Override
public JsonElement serialize
(SourceClass src, Type typeOfSrc, JsonSerializationContext context) {
String otherIntValueName = "otherIntValue";
String otherStringValueName = "otherStringValue";
JsonObject jObject = new JsonObject();
jObject.addProperty(otherIntValueName, src.getIntValue());
jObject.addProperty(otherStringValueName, src.getStringValue());
return jObject;
}
}4. 在序列化實體時忽略字段
現在,我們將在執行序列化時完全忽略字段:
@Test
public void givenIgnoringAField_whenSerializingWithCustomSerializer_thenFieldIgnored() {
SourceClass sourceObject = new SourceClass(7, "seven");
GsonBuilder gsonBuildr = new GsonBuilder();
gsonBuildr.registerTypeAdapter(SourceClass.class, new IgnoringFieldsSerializer());
String jsonString = gsonBuildr.create().toJson(sourceObject);
String expectedResult = "{"intValue":7}";
assertEquals(expectedResult, jsonString);
}類似於之前的示例,我們在這裏也使用了自定義序列化器:
public class IgnoringFieldsSerializer implements JsonSerializer<SourceClass> {
@Override
public JsonElement serialize
(SourceClass src, Type typeOfSrc, JsonSerializationContext context) {
String intValue = "intValue";
JsonObject jObject = new JsonObject();
jObject.addProperty(intValue, src.getIntValue());
return jObject;
}
}請注意,我們可能需要在無法修改實體源碼或字段僅應在非常特定情況下被忽略的情況下執行此操作。否則,我們可以更輕鬆地通過在實體類上直接添加註釋來忽略該字段。
5. 如果字段滿足自定義條件則僅序列化它
最後,讓我們分析一個更高級的用例——我們只想在字段滿足特定自定義條件時才進行序列化。
例如,我們只在整數值為正時才進行序列化,如果為負數則直接跳過:
@Test
public void givenUsingCustomDeserializer_whenFieldNotMatchesCriteria_thenIgnored() {
SourceClass sourceObject = new SourceClass(-1, "minus 1");
GsonBuilder gsonBuildr = new GsonBuilder();
gsonBuildr.registerTypeAdapter(SourceClass.class,
new IgnoringFieldsNotMatchingCriteriaSerializer());
Gson gson = gsonBuildr.create();
Type sourceObjectType = new TypeToken<SourceClass>() {}.getType();
String jsonString = gson.toJson(sourceObject, sourceObjectType);
String expectedResult = "{"stringValue":"minus 1"}";
assertEquals(expectedResult, jsonString);
}當然,我們在這裏也使用了 自定義序列化器:
public class IgnoringFieldsNotMatchingCriteriaSerializer
implements JsonSerializer<SourceClass> {
@Override
public JsonElement serialize
(SourceClass src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject jObject = new JsonObject();
// Criteria: intValue >= 0
if (src.getIntValue() >= 0) {
String intValue = "intValue";
jObject.addProperty(intValue, src.getIntValue());
}
String stringValue = "stringValue";
jObject.addProperty(stringValue, src.getStringValue());
return jObject;
}
}這就是使用 Gson 進行序列化的 5 個常見用例。