【问题标题】:Serializing Generic Scala Types with Gson使用 Gson 序列化通用 Scala 类型
【发布时间】:2014-11-05 17:07:34
【问题描述】:

我想使用 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\"}}")
  }

}

【问题讨论】:

    标签: json scala generics gson


    【解决方案1】:

    我在这里找到了答案: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\"}}")
      }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-07
      • 2015-07-16
      • 1970-01-01
      相关资源
      最近更新 更多