草庐IT

java - gson - 如何在序列化任何类型的对象时包含类名属性

coder 2024-03-16 原文

开始意识到在我的应用程序中序列化对象时,我需要将类名作为属性包含在内。如果我为任何序列化的非原始对象添加类名属性,那可能是最好的。

我看到这是 Genson 中的内置功能,使用 useClassMetadata 方法。但是我已经在我的项目中使用了 gson,所以如果我能坚持使用它将会受益匪浅。

这是我目前的尝试:

package com.mycompany.javatest;

import com.google.gson.*;
import java.lang.reflect.*;

public class JavaTest {

    public static class GenericSerializer implements JsonSerializer<Object>, JsonDeserializer<Object> {

        private static final String CLASS_PROPERTY_NAME = "class";

        @Override
        public JsonElement serialize(Object src, Type typeOfSrc,
                                     JsonSerializationContext context) {

            JsonElement retValue = context.serialize(src);
            if (retValue.isJsonObject()) {
                retValue.getAsJsonObject().addProperty(CLASS_PROPERTY_NAME, src.getClass().getName());
            }
            return retValue;
        }

        @Override
        public Object deserialize(JsonElement json, Type typeOfT,
                                  JsonDeserializationContext context) throws JsonParseException {

            Class actualClass;
            if (json.isJsonObject()) {
                JsonObject jsonObject = json.getAsJsonObject();
                String className = jsonObject.get(CLASS_PROPERTY_NAME).getAsString();

                try {
                    actualClass = Class.forName(className);
                }
                catch (ClassNotFoundException e) {
                    e.printStackTrace();
                    throw new JsonParseException(e.getMessage());
                }
            }
            else {
                actualClass = typeOfT.getClass();
            }
            return context.deserialize(json, actualClass);
        }
    }

    public static class MyClass {

        private final String name = "SpongePants SquareBob";

    }

    public static void main(String[] args) {

        MyClass obj = new MyClass();

        GsonBuilder gb = new GsonBuilder();
        gb.registerTypeAdapter(Object.class, new GenericSerializer());
        Gson gson = gb.create();

        System.out.println(gson.toJson(obj, Object.class));

    }
}

打印

{"name":"SpongePants SquareBob"}

我要打印

{"name":"SpongePants SquareBob","class":"com.mycompany.javatest$MyClass"}

编辑: 另一次尝试(这次使用 GsonFire)

package com.mycompany.javatest;

import com.google.gson.*;
import io.gsonfire.*;

public class JavaTest {

    public static class DummyData {

        private final String someData = "1337";

    }

    private static final String CLASS_PROPERTY_NAME = "class";

    public static void main(String[] args) {

        GsonFireBuilder gfb = new GsonFireBuilder();
        gfb.registerPostProcessor(Object.class, new PostProcessor<Object>() {

                              @Override
                              public void postDeserialize(Object t, JsonElement je, Gson gson) {
                                  // Ignore
                              }

                              @Override
                              public void postSerialize(JsonElement je, Object t, Gson gson) {
                                  if (je.isJsonObject()) {
                                      je.getAsJsonObject().add(CLASS_PROPERTY_NAME, new JsonPrimitive(t.getClass().getTypeName()));
                                  }
                              }

                          });

        gfb.registerTypeSelector(Object.class, (JsonElement je) -> {
            System.out.println(je);
                             if (je.isJsonObject()) {
                                 try {
                                     return Class.forName(je.getAsJsonObject().get(CLASS_PROPERTY_NAME).getAsString());
                                 }
                                 catch (ClassNotFoundException ex) {
                                     ex.printStackTrace();
                                 }
                             }

                             return null;
                         });

        Gson gson = gfb.createGson();

        DummyData dd = new DummyData();
        String json = gson.toJson(dd);
        System.out.println(json);

        DummyData dd2 = (DummyData) gson.fromJson(json, Object.class); // <-- gives me a ClassCastException

    }

}

最佳答案

又一个答案。花了一点时间。

旁注:如果您递归地使用反射来计算您的类中的字段,则上述解决方案将有效。然后使用特殊的序列化器序列化那些序列化器,同时为父对象使用一个单独的序列化器。这将避免计算器溢出。

话虽如此 - 我是一个懒惰的开发人员,所以我喜欢懒惰地做事。我正在为您调整谷歌解决方案。

注意:请对此进行测试并根据您的需要进行调整。这是一个原型(prototype),我没有清理不必要的代码或检查可能的问题>

代码原始出处:

https://github.com/google/gson/blob/master/extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java

因此,这是基于 RuntimeTypeAdapterFactory .该工厂由 google 提供,其目的是支持分层反序列化。为此,您需要注册一个基类和所有子类,并使用您希望添加为标​​识符的属性。如果您阅读 javadoc,这会变得更加清晰。

这显然为我们提供了我们想要的东西:递归地为可以处理这些的类类型注册不同的适配器,而不是在循环中运行并导致堆栈溢出。有一个重要问题:您必须注册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

尽管您必须进行调整才能使它适合您,所以我制作了一份副本。该副本会完全编译,您只需将其粘贴到您的代码中,即可省去额外的依赖项。

此代码的重要部分如下:(我特意将它们保留但注释掉以便您可以分辨)

create(Gson gson, TypeToken<R> type)

检查原始类型是否可从 String 类分配。您希望将它应用于每个类对象,因此它会处理这个问题。请注意,如果该类型已在类中注册,则之前的代码将查找 - 不再需要(因此不需要变量;您应该清理代码)

@Override public void write(JsonWriter out, R value) throws IOException { :

首先,我们去掉标签。我们的标签现在是并将永远是源类型的名称。这是在以下情况下完成的:

String label = srcType.getName();

其次,我们必须区分原始类型和对象类型。 Gson 世界中的原始类型是字符串、整数等。这意味着我们上面的检查(添加适配器)没有捕捉到这些对象类型实际上是原始类型的事实。所以我们这样做:

if(jsonTree.isJsonPrimitive()) {
            Streams.write(jsonTree, out);

这会解决这个问题。如果它是原始的,只需将树写入流即可。如果不是,则我们将所有其他字段 类字段写入其中。

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

如您所见,字符串、长整数、整数已正确创建。每个类对象递归地也得到了它的类名。

这是一种通用方法,应该适用于您创建的所有内容。但是,如果您决定接受这个,请帮我写一些单元测试;)就像我之前提到的,我制作了这个实现的原型(prototype)。

希望这能让我满意 :)

问候,

阿图尔

关于java - gson - 如何在序列化任何类型的对象时包含类名属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39999278/

有关java - gson - 如何在序列化任何类型的对象时包含类名属性的更多相关文章

  1. ruby - 如何在 Ruby 中顺序创建 PI - 2

    出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

  2. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  3. ruby - 如何在 buildr 项目中使用 Ruby 代码? - 2

    如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby​​

  4. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  5. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  6. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  7. ruby - 如何在续集中重新加载表模式? - 2

    鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende

  8. ruby - 如何在 Ruby 中拆分参数字符串 Bash 样式? - 2

    我正在为一个项目制作一个简单的shell,我希望像在Bash中一样解析参数字符串。foobar"helloworld"fooz应该变成:["foo","bar","helloworld","fooz"]等等。到目前为止,我一直在使用CSV::parse_line,将列分隔符设置为""和.compact输出。问题是我现在必须选择是要支持单引号还是双引号。CSV不支持超过一个分隔符。Python有一个名为shlex的模块:>>>shlex.split("Test'helloworld'foo")['Test','helloworld','foo']>>>shlex.split('Test"

  9. ruby - 如何在 Lion 上安装 Xcode 4.6,需要用 RVM 升级 ruby - 2

    我实际上是在尝试使用RVM在我的OSX10.7.5上更新ruby,并在输入以下命令后:rvminstallruby我得到了以下回复:Searchingforbinaryrubies,thismighttakesometime.Checkingrequirementsforosx.Installingrequirementsforosx.Updatingsystem.......Errorrunning'requirements_osx_brew_update_systemruby-2.0.0-p247',pleaseread/Users/username/.rvm/log/138121

  10. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

随机推荐