Gson序列化Map子类,也有明确定义的属性

问题描述 投票:1回答:1

我有一个生成的java bean的集合,其中每个bean定义一个或多个字段,加上它的子类HashMap<String, T>,其中T是参数化类型。生成的字段在JSON schema中对显式定义的模式属性进行建模,并且HashMap的子类化用于支持特定类型的其他“任意”属性(由JSON模式的“additionalProperties”字段指定,适用于熟悉JSON模式的人员) )。以下是生成的bean的示例:

public class MyModel extends HashMap<String, Foo> {
    private String prop1;
    private Long prop2;

    public String getProp1() {
        return prop1;
    }

    public void setProp1(String value) {
        this.prop1 = value;
    }

    public Long getProp2() {
        return prop2;
    }

    public void setProp2(Long prop2) {
        this.prop2 = prop2;
    }
}

在此示例中,用户可以将prop1prop2设置为普通bean属性,还可以通过FooMap方法设置put()类型的任意属性,其中Foo只是其他一些用户定义的类型。

问题在于,默认情况下,Gson序列化这些生成的bean的实例,使得只有Map条目包含在生成的JSON字符串中,并且忽略显式定义的字段。

这是一个代码片段,显示我如何使用Gson序列化对象:

    private String serialize(Object obj) {
        return new Gson().toJson(obj);
    }

从调试序列化路径,我可以看到Gson正在选择其内部MapTypeAdapterFactory来执行序列化,这是有意义的,因为只有Map条目最终在JSON字符串中。另外,如果我序列化一个不是HashMap子类的bean,那么Gson会选择它的内部ReflectiveTypeAdapterFactory

我认为我需要的是实现我自己的自定义类型适配器,它基本上结合了ReflectiveMap类型适配器工厂的功能。这听起来像个好计划吗?有没有其他人做过类似的事情,或许可以提供一个例子让我开始?这将是我第一次涉足Gson自定义类型适配器。

java json serialization gson jsonserializer
1个回答
0
投票

我们知道默认情况下,Gson将这些对象视为Map,因此我们可以使用它来序列化所有key-value对,并使用reflection手动序列化其余的对象。

简单的序列化器实现如下所示:

class MixedJsonSerializer implements JsonSerializer<Object> {

    @Override
    public JsonElement serialize(Object src, Type typeOfSrc, JsonSerializationContext context) {
        JsonObject json = serialiseAsMap(src, context);
        serialiseAsPojo(src, context, json);

        return json;
    }

    private JsonObject serialiseAsMap(Object src, JsonSerializationContext context) {
        return (JsonObject) context.serialize(src, Map.class);
    }

    private void serialiseAsPojo(Object src, JsonSerializationContext context, JsonObject mapElement) {
        Method[] methods = ReflectionUtils.getAllDeclaredMethods(src.getClass());
        for (Method method : methods) {
            if (shouldSerialise(method)) {
                final Object result = ReflectionUtils.invokeMethod(method, src);
                final String fieldName = getFieldName(method);
                mapElement.add(fieldName, context.serialize(result));
            }
        }
    }

    private boolean shouldSerialise(Method method) {
        final String name = method.getName();

        return method.getParameterCount() == 0 &&
                ReflectionUtils.USER_DECLARED_METHODS.matches(method) &&
                !IGNORED_METHODS.contains(name) &&
                (name.startsWith("is") || name.startsWith("get"));
    }

    private static final List<String> IGNORED_METHODS = Arrays.asList("isEmpty", "length"); //etc

    private String getFieldName(Method method) {
        final String field = method.getName().replaceAll("^(is|get)", "");

        return StringUtils.uncapitalize(field);
    }
}

最复杂的部分是找到所有POJO getter并在给定对象上调用它们。例如,我使用reflection API库中的Spring。下面你可以找到如何使用它的例子(我假设所有POJO类扩展HashMap):

import com.model.Foo;
import com.model.Pojo;
import com.model.Pojo1;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class GsonApp {

    public static void main(String[] args) {
        System.out.println("Pojo + Map: ");
        Pojo pojo = new Pojo();
        pojo.put("character1", new Foo("Morty", 15));
        pojo.put("character2", new Foo("Rick", 60));

        System.out.println(serialize(pojo));
        System.out.println();

        System.out.println("Map only: ");
        Pojo1 pojo1 = new Pojo1();
        pojo1.put("int1", 1);
        pojo1.put("int2", 22);
        System.out.println(serialize(pojo1));
        System.out.println();

        System.out.println("Pojo only:");
        System.out.println(serialize(new Pojo()));
        System.out.println();
    }

    private static final Gson gson = createGson();

    private static Gson createGson() {
        MixedJsonSerializer adapter = new MixedJsonSerializer();
        return new GsonBuilder()
                .setPrettyPrinting()
                // in case you have many classes you need to use reflection
                // to register adapter for each needed class.
                .registerTypeAdapter(Pojo.class, adapter)
                .registerTypeAdapter(Pojo1.class, adapter)
                .create();
    }

    private static String serialize(Object obj) {
        return gson.toJson(obj);
    }
}

上面的代码打印:

Pojo + Map: 
{
  "character2": {
    "name": "Rick",
    "age": 60
  },
  "character1": {
    "name": "Morty",
    "age": 15
  },
  "prop1": "Value1",
  "ten": 10,
  "foo": {
    "name": "Test",
    "age": 123
  }
}

Map only: 
{
  "int2": 22,
  "int1": 1
}

Pojo only:
{
  "prop1": "Value1",
  "ten": 10,
  "foo": {
    "name": "Test",
    "age": 123
  }
}

如果您需要手动注册许多类,则可以使用反射来扫描给定的包并为它们注册序列化程序。见:Can you find all classes in a package using reflection?

© www.soinside.com 2019 - 2024. All rights reserved.