使用Gson序列化通用Scala类型

时间:2014-11-05 17:07:34

标签: json scala generics gson

我想使用Gson序列化程序将一个通用scala类的实例序列化为Json。序列化普通对象时,序列化通用对象不行。下面的第一个测试成功,第二个测试失败:

序列化下面的变量myGeneric只会给出字符串' {" value":{}}'而不是测试中的预期。关于如何正确地做到这一点的任何想法?

class MyGeneric[T](t : T) {
  val value : T = t;
}

class Bla(v1: String) {
  val value1 = v1
}

class GsonGenericTest extends FlatSpec with Matchers {

  behavior of "Gson"

  it should "be able to serialize plain objects" in {
    val myObject = new Bla("value1")
    new Gson().toJson(myObject) should be ("{\"value1\":\"value1\"}")
  }

  it should "be able to serialize generic objects" in {
    val myGeneric = new MyGeneric[Bla](new Bla("value1"))
    new Gson().toJson(myGeneric) should be ("{\"value\":{\"value1\":\"value1\"}}")
  }

}

1 个答案:

答案 0 :(得分:0)

我在这里找到答案:http://www.studytrails.com/java/json/java-google-json-serializing-classes-with-generic-type.jsp

这可以转换为Scala,使测试用例的工作方式如下:

class MyGeneric[T](t : T) {
  val value : T = t;
}

class Bla(v1: String) {
  val value1 = v1
}

class GsonGenericTest extends FlatSpec with Matchers {

  behavior of "Gson"

  it should "be able to serialize plain objects" in {
    val myObject = new Bla("value1")
    new Gson().toJson(myObject) should be ("{\"value1\":\"value1\"}")
  }

  it should "be able to serialize generic objects" in {
    val myGeneric = new MyGeneric[Bla](new Bla("value1"))
    val myGenericType : Type = new TypeToken[MyGeneric[Bla]]() { }.getType();
    val json = new Gson().toJson(myGeneric, myGenericType)
    json should be ("{\"value\":{\"value1\":\"value1\"}}")
  }

}