Glu*_*bus 2 java serialization json gson
所以对于这个小程序,我正在写我正在寻找解析Twitter的推文流.我使用Gson库,效果很好.Gson无法解析Twitters created_at datetime字段,因此我必须编写一个JsonDserializer需要通过GsonBuilder以下方式向解析器注册的自定义:
new GsonBuilder().registerTypeAdatapter(DateTime.class, <myCustomDeserializerType>)
Run Code Online (Sandbox Code Playgroud)
现在我的解串器运行良好,我能够解析Twitter的流.
但是,我试图用单元测试来覆盖我的程序,所以应该包含这个自定义反序列化器.
由于良好的单元测试是一个很好的隔离测试,我不想用一个Gson对象注册它,之后我将解析一个json字符串.我不希望是创造我的解串器的实例,只是传递表示日期时间的一般串,这样我就可以测试解串器没有它正在与别的集成.
JsonDeserializer的deserialize方法的签名如下:
deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext)
Run Code Online (Sandbox Code Playgroud)
假设我要解析以下数据:'Mon Mar 27 14:09:47 +0000 2017'.我如何转换输入数据以正确测试我的反序列化器.
我不是在寻找实际解析这个日期的代码,我已经覆盖了那个部分.我问我如何能够满足deserialize方法的签名,以便我可以模拟它在Gson其中的使用.
JsonSerializer并且JsonDeserializer紧密绑定到Gson JSON树模型和特定Gson配置(de)序列化上下文,它提供了一组可以(反)序列化的类型.因此,完成单元测试JsonSerializer并且JsonDeserializer相当困难.
在您的某处考虑以下JSON文档src/test/resources/.../zoned-date-time.json:
"Mon Mar 27 14:09:47 +0000 2017"
Run Code Online (Sandbox Code Playgroud)
这是一个非常有效的JSON文档,除了简单的单个字符串外,它没有任何内容.上述格式的日期/时间格式化程序可以在Java 8中实现,如下所示:
final class CustomPatterns {
private CustomPatterns() {
}
private static final Map<Long, String> dayOfWeek = ImmutableMap.<Long, String>builder()
.put(1L, "Mon")
.put(2L, "Tue")
.put(3L, "Wed")
.put(4L, "Thu")
.put(5L, "Fri")
.put(6L, "Sat")
.put(7L, "Sun")
.build();
private static final Map<Long, String> monthOfYear = ImmutableMap.<Long, String>builder()
.put(1L, "Jan")
.put(2L, "Feb")
.put(3L, "Mar")
.put(4L, "Apr")
.put(5L, "May")
.put(6L, "Jun")
.put(7L, "Jul")
.put(8L, "Aug")
.put(9L, "Sep")
.put(10L, "Oct")
.put(11L, "Nov")
.put(12L, "Dec")
.build();
static final DateTimeFormatter customDateTimeFormatter = new DateTimeFormatterBuilder()
.appendText(DAY_OF_WEEK, dayOfWeek)
.appendLiteral(' ')
.appendText(MONTH_OF_YEAR, monthOfYear)
.appendLiteral(' ')
.appendValue(DAY_OF_MONTH, 1, 2, NOT_NEGATIVE)
.appendLiteral(' ')
.appendValue(HOUR_OF_DAY, 2)
.appendLiteral(':')
.appendValue(MINUTE_OF_HOUR, 2)
.appendLiteral(':')
.appendValue(SECOND_OF_MINUTE, 2)
.appendLiteral(' ')
.appendOffset("+HHMM", "+0000")
.appendLiteral(' ')
.appendValue(YEAR)
.toFormatter();
}
Run Code Online (Sandbox Code Playgroud)
现在考虑以下JSON反序列化器ZonedDateTime:
final class ZonedDateTimeJsonDeserializer
implements JsonDeserializer<ZonedDateTime> {
private static final JsonDeserializer<ZonedDateTime> zonedDateTimeJsonDeserializer = new ZonedDateTimeJsonDeserializer();
private ZonedDateTimeJsonDeserializer() {
}
static JsonDeserializer<ZonedDateTime> getZonedDateTimeJsonDeserializer() {
return zonedDateTimeJsonDeserializer;
}
@Override
public ZonedDateTime deserialize(final JsonElement jsonElement, final Type type, final JsonDeserializationContext context)
throws JsonParseException {
try {
final String s = context.deserialize(jsonElement, String.class);
return ZonedDateTime.parse(s, customDateTimeFormatter);
} catch ( final DateTimeParseException ex ) {
throw new JsonParseException(ex);
}
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,我通过上下文对字符串进行了解释,意图强调更复杂的JsonDeserializer实例可能会严重依赖它.现在让我们做一些JUnit测试来测试它:
public final class ZonedDateTimeJsonDeserializerTest {
private static final TypeToken<ZonedDateTime> zonedDateTimeTypeToken = new TypeToken<ZonedDateTime>() {
};
private static final ZonedDateTime expectedZonedDateTime = ZonedDateTime.of(2017, 3, 27, 14, 9, 47, 0, UTC);
@Test
public void testDeserializeIndirectlyViaAutomaticTypeAdapterBinding()
throws IOException {
final JsonDeserializer<ZonedDateTime> unit = getZonedDateTimeJsonDeserializer();
final Gson gson = new GsonBuilder()
.registerTypeAdapter(ZonedDateTime.class, unit)
.create();
try ( final JsonReader jsonReader = getPackageResourceJsonReader(ZonedDateTimeJsonDeserializerTest.class, "zoned-date-time.json") ) {
final ZonedDateTime actualZonedDateTime = gson.fromJson(jsonReader, ZonedDateTime.class);
assertThat(actualZonedDateTime, is(expectedZonedDateTime));
}
}
@Test
public void testDeserializeIndirectlyViaManualTypeAdapterBinding()
throws IOException {
final JsonDeserializer<ZonedDateTime> unit = getZonedDateTimeJsonDeserializer();
final Gson gson = new Gson();
final TypeAdapterFactory typeAdapterFactory = newFactoryWithMatchRawType(zonedDateTimeTypeToken, unit);
final TypeAdapter<ZonedDateTime> dateTypeAdapter = typeAdapterFactory.create(gson, zonedDateTimeTypeToken);
try ( final JsonReader jsonReader = getPackageResourceJsonReader(ZonedDateTimeJsonDeserializerTest.class, "zoned-date-time.json") ) {
final ZonedDateTime actualZonedDateTime = dateTypeAdapter.read(jsonReader);
assertThat(actualZonedDateTime, is(expectedZonedDateTime));
}
}
@Test
public void testDeserializeDirectlyWithMockedContext()
throws IOException {
final JsonDeserializer<ZonedDateTime> unit = getZonedDateTimeJsonDeserializer();
final JsonDeserializationContext mockContext = mock(JsonDeserializationContext.class);
when(mockContext.deserialize(any(JsonElement.class), eq(String.class))).thenAnswer(iom -> {
final JsonElement jsonElement = (JsonElement) iom.getArguments()[0];
return jsonElement.getAsJsonPrimitive().getAsString();
});
final JsonParser parser = new JsonParser();
try ( final JsonReader jsonReader = getPackageResourceJsonReader(ZonedDateTimeJsonDeserializerTest.class, "zoned-date-time.json") ) {
final JsonElement jsonElement = parser.parse(jsonReader);
final ZonedDateTime actualZonedDateTime = unit.deserialize(jsonElement, ZonedDateTime.class, mockContext);
assertThat(actualZonedDateTime, is(expectedZonedDateTime));
}
verify(mockContext).deserialize(any(JsonPrimitive.class), eq(String.class));
verifyNoMoreInteractions(mockContext);
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,这里的每个测试都需要构建一些Gson配置,以便让反序列化上下文起作用,或者后者必须被模拟.几乎要测试一个简单的单元.
Gson中JSON树模型的替代方案是面向流的类型适配器,它不需要构造整个JSON树,因此您可以轻松地直接从/向JSON流读取或写入,从而使您的(反)序列化更快,更少记忆消耗.特别是,对于简单的情况,比如琐碎的字符串<==> FooBar转换.
final class ZonedDateTimeTypeAdapter
extends TypeAdapter<ZonedDateTime> {
private static final TypeAdapter<ZonedDateTime> zonedDateTimeTypeAdapter = new ZonedDateTimeTypeAdapter().nullSafe();
private ZonedDateTimeTypeAdapter() {
}
static TypeAdapter<ZonedDateTime> getZonedDateTimeTypeAdapter() {
return zonedDateTimeTypeAdapter;
}
@Override
public void write(final JsonWriter out, final ZonedDateTime zonedDateTime) {
throw new UnsupportedOperationException();
}
@Override
public ZonedDateTime read(final JsonReader in)
throws IOException {
try {
final String s = in.nextString();
return ZonedDateTime.parse(s, customDateTimeFormatter);
} catch ( final DateTimeParseException ex ) {
throw new JsonParseException(ex);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是上面的类型适配器的简单单元测试:
public final class ZonedDateTimeTypeAdapterTest {
private static final ZonedDateTime expectedZonedDateTime = ZonedDateTime.of(2017, 3, 27, 14, 9, 47, 0, UTC);
@Test(expected = UnsupportedOperationException.class)
public void testWrite() {
final TypeAdapter<ZonedDateTime> unit = getZonedDateTimeTypeAdapter();
unit.toJsonTree(expectedZonedDateTime);
}
@Test
public void testRead()
throws IOException {
final TypeAdapter<ZonedDateTime> unit = getZonedDateTimeTypeAdapter();
try ( final Reader reader = getPackageResourceReader(ZonedDateTimeTypeAdapterTest.class, "zoned-date-time.json") ) {
final ZonedDateTime actualZonedDateTime = unit.fromJson(reader);
assertThat(actualZonedDateTime, is(expectedZonedDateTime));
}
}
}
Run Code Online (Sandbox Code Playgroud)
对于简单的情况,我肯定会使用类型适配器,但是它们可能有点难以实现.您还可以参考Gson单元测试以获取更多信息.