GSON平面向下Map到其他字段

lnxxn5zx  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(150)

我有一个Android应用程序,它使用Retrofit for API。我有一个类,看起来像:

class Foo {
   String bar;
   Map<String, String> map;
}

当GSON创建JSON时,如下所示:

{
   "bar":"value",
   "map": {
      "key1":"value1"
   }
}

是否可以将JSON序列化更改为:

{
   "bar":"value",
   "key1":"value1"
}
  • 谢谢-谢谢
au9on6nz

au9on6nz1#

下面是如何使用Gson来实现平面化:
第一个
我已经添加了一些注解来解释“是什么”和“如何”。但是即使没有注解,它也很容易理解。单元测试示例:

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;
        }

    }

}

上面的代码可以通过使用Java8流、一些Guava或Apache Commons的东西来简化,但是只要你在Android上,你可能只需要一些纯Java6。

相关问题