public final class FlatteningTypeAdapterFactoryTest {
private static final Gson gson = new GsonBuilder()
.disableHtmlEscaping()
.disableInnerClassSerialization()
.registerTypeAdapterFactory(FlatteningTypeAdapterFactory.getInstance())
.create();
@Test
public void test() {
final Object source = new Bar(
"foo-value",
Map.of("k1", "v1", "k2", "v2", "k3", "v3"),
"bar-value",
Map.of("k4", "v4")
);
final JsonObject expected = new JsonObject();
expected.add("foo", new JsonPrimitive("foo-value"));
expected.add("k1", new JsonPrimitive("v1"));
expected.add("k2", new JsonPrimitive("v2"));
expected.add("k3", new JsonPrimitive("v3"));
expected.add("bar", new JsonPrimitive("bar-value"));
expected.add("k4", new JsonPrimitive("v4"));
final JsonElement actual = gson.toJsonTree(source);
Assertions.assertEquals(expected, actual);
}
private static class Foo {
private final String foo;
@Flatten
private final Map<String, String> fooMap;
private Foo(final String foo, final Map<String, String> fooMap) {
this.foo = foo;
this.fooMap = fooMap;
}
}
private static class Bar
extends Foo {
private final String bar;
@Flatten
private final Map<String, String> barMap;
private final transient String thisMustNotBeSerialized = "This must not be serialized";
private Bar(final String foo, final Map<String, String> fooMap, final String bar, final Map<String, String> barMap) {
super(foo, fooMap);
this.bar = bar;
this.barMap = barMap;
}
}
}
1条答案
按热度按时间au9on6nz1#
下面是如何使用Gson来实现平面化:
第一个
我已经添加了一些注解来解释“是什么”和“如何”。但是即使没有注解,它也很容易理解。单元测试示例:
上面的代码可以通过使用Java8流、一些Guava或Apache Commons的东西来简化,但是只要你在Android上,你可能只需要一些纯Java6。