还有一个答案。花了更长的时间。
旁注:如果您递归地使用反射来计算类中的字段,则上述解决方案将有效。然后使用特殊的序列化器序列化它们,同时为父对象使用单独的序列化器。这将避免堆栈溢出。
话虽如此,我是一个懒惰的开发人员,所以我喜欢偷懒做事。我正在为您调整谷歌解决方案。
注意:请对此进行测试并根据您的需要进行调整。这是一个原型,我还没有清理不必要的代码或检查可能的问题>
代码原始来源:
https://github.com/google/gson/blob/master/extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java
所以,这是基于RuntimeTypeAdapterFactory
。这个工厂是由google提供的,其目的是支持分层反序列化。为此,您需要注册一个基类和所有子类,以及您想要添加为标识符的属性。如果你阅读 javadocs,这会变得更清楚。
这显然为我们提供了我们想要的东西:为可以处理这些的类类型递归地注册不同的适配器,同时不会循环运行并导致堆栈溢出。有一个重要的问题:你必须注册ALL子类。这显然是不合适的(尽管有人可能会争辩说你可以进行类路径解析并在启动时简单地添加所有类以便能够在任何地方使用它)。所以我研究了源代码并更改了代码以动态地执行此操作。请注意,谷歌警告不要这样做 - 按照你自己的条件使用它:)
这是我的工厂:
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.internal.Streams;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
/**
* Adapts values whose runtime type may differ from their declaration type. This
* is necessary when a field's type is not the same type that GSON should create
* when deserializing that field. For example, consider these types:
* <pre> {@code
* abstract class Shape {
* int x;
* int y;
* }
* class Circle extends Shape {
* int radius;
* }
* class Rectangle extends Shape {
* int width;
* int height;
* }
* class Diamond extends Shape {
* int width;
* int height;
* }
* class Drawing {
* Shape bottomShape;
* Shape topShape;
* }
* }</pre>
* <p>Without additional type information, the serialized JSON is ambiguous. Is
* the bottom shape in this drawing a rectangle or a diamond? <pre> {@code
* {
* "bottomShape": {
* "width": 10,
* "height": 5,
* "x": 0,
* "y": 0
* },
* "topShape": {
* "radius": 2,
* "x": 4,
* "y": 1
* }
* }}</pre>
* This class addresses this problem by adding type information to the
* serialized JSON and honoring that type information when the JSON is
* deserialized: <pre> {@code
* {
* "bottomShape": {
* "type": "Diamond",
* "width": 10,
* "height": 5,
* "x": 0,
* "y": 0
* },
* "topShape": {
* "type": "Circle",
* "radius": 2,
* "x": 4,
* "y": 1
* }
* }}</pre>
* Both the type field name ({@code "type"}) and the type labels ({@code
* "Rectangle"}) are configurable.
*
* <h3>Registering Types</h3>
* Create a {@code RuntimeTypeAdapterFactory} by passing the base type and type field
* name to the {@link #of} factory method. If you don't supply an explicit type
* field name, {@code "type"} will be used. <pre> {@code
* RuntimeTypeAdapterFactory<Shape> shapeAdapterFactory
* = RuntimeTypeAdapterFactory.of(Shape.class, "type");
* }</pre>
* Next register all of your subtypes. Every subtype must be explicitly
* registered. This protects your application from injection attacks. If you
* don't supply an explicit type label, the type's simple name will be used.
* <pre> {@code
* shapeAdapter.registerSubtype(Rectangle.class, "Rectangle");
* shapeAdapter.registerSubtype(Circle.class, "Circle");
* shapeAdapter.registerSubtype(Diamond.class, "Diamond");
* }</pre>
* Finally, register the type adapter factory in your application's GSON builder:
* <pre> {@code
* Gson gson = new GsonBuilder()
* .registerTypeAdapterFactory(shapeAdapterFactory)
* .create();
* }</pre>
* Like {@code GsonBuilder}, this API supports chaining: <pre> {@code
* RuntimeTypeAdapterFactory<Shape> shapeAdapterFactory = RuntimeTypeAdapterFactory.of(Shape.class)
* .registerSubtype(Rectangle.class)
* .registerSubtype(Circle.class)
* .registerSubtype(Diamond.class);
* }</pre>
*/
public final class RuntimeClassNameTypeAdapterFactory<T> implements TypeAdapterFactory {
private final Class<?> baseType;
private final String typeFieldName;
private final Map<String, Class<?>> labelToSubtype = new LinkedHashMap<String, Class<?>>();
private final Map<Class<?>, String> subtypeToLabel = new LinkedHashMap<Class<?>, String>();
private RuntimeClassNameTypeAdapterFactory(Class<?> baseType, String typeFieldName) {
if (typeFieldName == null || baseType == null) {
throw new NullPointerException();
}
this.baseType = baseType;
this.typeFieldName = typeFieldName;
}
/**
* Creates a new runtime type adapter using for {@code baseType} using {@code
* typeFieldName} as the type field name. Type field names are case sensitive.
*/
public static <T> RuntimeClassNameTypeAdapterFactory<T> of(Class<T> baseType, String typeFieldName) {
return new RuntimeClassNameTypeAdapterFactory<T>(baseType, typeFieldName);
}
/**
* Creates a new runtime type adapter for {@code baseType} using {@code "type"} as
* the type field name.
*/
public static <T> RuntimeClassNameTypeAdapterFactory<T> of(Class<T> baseType) {
return new RuntimeClassNameTypeAdapterFactory<T>(baseType, "class");
}
/**
* Registers {@code type} identified by {@code label}. Labels are case
* sensitive.
*
* @throws IllegalArgumentException if either {@code type} or {@code label}
* have already been registered on this type adapter.
*/
public RuntimeClassNameTypeAdapterFactory<T> registerSubtype(Class<? extends T> type, String label) {
if (type == null || label == null) {
throw new NullPointerException();
}
if (subtypeToLabel.containsKey(type) || labelToSubtype.containsKey(label)) {
throw new IllegalArgumentException("types and labels must be unique");
}
labelToSubtype.put(label, type);
subtypeToLabel.put(type, label);
return this;
}
/**
* Registers {@code type} identified by its {@link Class#getSimpleName simple
* name}. Labels are case sensitive.
*
* @throws IllegalArgumentException if either {@code type} or its simple name
* have already been registered on this type adapter.
*/
public RuntimeClassNameTypeAdapterFactory<T> registerSubtype(Class<? extends T> type) {
return registerSubtype(type, type.getSimpleName());
}
public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
final Map<String, TypeAdapter<?>> labelToDelegate
= new LinkedHashMap<String, TypeAdapter<?>>();
final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate
= new LinkedHashMap<Class<?>, TypeAdapter<?>>();
// && !String.class.isAssignableFrom(type.getRawType())
if(Object.class.isAssignableFrom(type.getRawType()) ) {
TypeAdapter<?> delegate = gson.getDelegateAdapter(this, type);
labelToDelegate.put("class", delegate);
subtypeToDelegate.put(type.getRawType(), delegate);
}
// for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) {
// TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue()));
// labelToDelegate.put(entry.getKey(), delegate);
// subtypeToDelegate.put(entry.getValue(), delegate);
// }
return new TypeAdapter<R>() {
@Override public R read(JsonReader in) throws IOException {
JsonElement jsonElement = Streams.parse(in);
JsonElement labelJsonElement = jsonElement.getAsJsonObject().remove(typeFieldName);
if (labelJsonElement == null) {
throw new JsonParseException("cannot deserialize " + baseType
+ " because it does not define a field named " + typeFieldName);
}
String label = labelJsonElement.getAsString();
@SuppressWarnings("unchecked") // registration requires that subtype extends T
TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label);
if (delegate == null) {
throw new JsonParseException("cannot deserialize " + baseType + " subtype named "
+ label + "; did you forget to register a subtype?");
}
return delegate.fromJsonTree(jsonElement);
}
@Override public void write(JsonWriter out, R value) throws IOException {
Class<?> srcType = value.getClass();
String label = srcType.getName();
@SuppressWarnings("unchecked") // registration requires that subtype extends T
TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType);
if (delegate == null) {
throw new JsonParseException("cannot serialize " + srcType.getName()
+ "; did you forget to register a subtype?");
}
JsonElement jsonTree = delegate.toJsonTree(value);
if(jsonTree.isJsonPrimitive()) {
Streams.write(jsonTree, out);
} else {
JsonObject jsonObject = jsonTree.getAsJsonObject();
if (jsonObject.has(typeFieldName)) {
throw new JsonParseException("cannot serialize " + srcType.getName()
+ " because it already defines a field named " + typeFieldName);
}
JsonObject clone = new JsonObject();
clone.add(typeFieldName, new JsonPrimitive(label));
for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) {
clone.add(e.getKey(), e.getValue());
}
Streams.write(clone, out);
}
}
}.nullSafe();
}
}
我已经为你添加了所有进口。这并没有(真正)发布在 Maven Central 中,尽管你可以在这里找到它:https://mvnrepository.com/artifact/org.danilopianini/gson-extras/0.1.0
不管怎样,你都必须进行调整才能让它为你工作,所以我复制了一份。副本已完全编译,您只需将其粘贴到代码中即可节省额外的依赖项。
这段代码的重要部分如下:(我故意将它们留在其中,但已注释掉,以便您可以看出)
in create(Gson gson, TypeToken<R> type)
检查原始类型是否可从 String 类分配。您希望将其应用于每个类对象,因此这可以解决这一问题。请注意,之前的代码将查找该类型是否已在类中注册 - 不再需要(因此不需要变量;您应该清理代码)
in @Override public void write(JsonWriter out, R value) throws IOException {
:
首先,我们去掉标签。我们的标签现在是并且永远是源类型的名称。这是在以下位置完成的:
String label = srcType.getName();
其次,我们必须区分原始类型和对象类型。 Gson 世界中的基本类型是字符串、整数等。这意味着我们上面的检查(添加适配器)没有捕获这些对象类型实际上是原始类型的事实。所以我们这样做:
if(jsonTree.isJsonPrimitive()) {
Streams.write(jsonTree, out);
这可以解决这个问题。如果是原始的,只需将树写入流中即可。如果不是,我们然后写入所有其他字段AND类字段放入其中。
JsonObject clone = new JsonObject();
clone.add(typeFieldName, new JsonPrimitive(label));
for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) {
clone.add(e.getKey(), e.getValue());
}
Streams.write(clone, out);
Fewww - 现在终于解决了这个问题。这是证明我的代码可以执行(我相信)您希望它执行的操作的示例;)
public class GsonClassNameTest {
static Gson create = new GsonBuilder().registerTypeAdapterFactory(RuntimeClassNameTypeAdapterFactory.of(Object.class)).create();
public static void main(String[] args) {
String json = create.toJson(new X());
System.out.println(json);
}
public static class X {
public String test = "asd";
public int xyz = 23;
public Y y_class = new Y();
}
public static class Y {
String yTest = "asd2";
Z zTest = new Z();
}
public static class Z {
long longVal = 25;
double doubleTest = 2.4;
}
}
现在为您输出这个 json:
{
"class":"google.GsonClassNameTest$X",
"test":"asd",
"xyz":23,
"y_class":{
"class":"google.GsonClassNameTest$Y",
"yTest":"asd2",
"zTest":{
"class":"google.GsonClassNameTest$Z",
"longVal":25,
"doubleTest":2.4
}
}
}
如您所见,字符串、长整型、整数已正确创建。每个类对象也递归地获取其类名。
这是一种通用方法,应该适用于您创建的所有内容。但是,如果您决定接受这个,请帮我一个忙,编写一些单元测试;)就像我之前提到的,我对这个实现进行了原型设计。
希望这能让我打勾:)
Regards,
Artur