简体   繁体   中英

Serializing Generic Scala Types with Gson

I would like to serialize an instance of a generic scala class as Json using the Gson serializer. While serializing a plain object works fine, serializing a generic object does not. The first test below succeeds, the second one fails:

Serializing the variable myGeneric below simply gives the String '{"value":{}}' instead of what is expected in the test. Any ideas on how to do it properly?

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\"}}")
  }

}

I found the answer here: http://www.studytrails.com/java/json/java-google-json-serializing-classes-with-generic-type.jsp

This can be translated to Scala to make the test case work as follows:

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\"}}")
  }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM