如何在 Scala 中使用 Gson 来序列化列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6785465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I use Gson in Scala to serialize a List?
提问by Kevin
I was hoping to use Scala and Gson together. It seems to mostly work, but when I do something like this, it treats the list as an object, not an array:
我希望同时使用 Scala 和 Gson。它似乎主要工作,但是当我做这样的事情时,它将列表视为一个对象,而不是一个数组:
case class MyType (val x:String, val y:List[SomeOtherType]) {
def toJson() = new Gson().toJson(this)
}
And my JSON turns out something like this:
我的 JSON 结果是这样的:
{
"x":"whatever",
"y": {
}
}
Normally Gson converts lists to arrays. I'm sure this is all because Gson doesn't know about Scala's collection classes, but any ideas on what I can do to make this work? Or other suggestions using Scala-native JSON libraries?
通常 Gson 将列表转换为数组。我确定这完全是因为 Gson 不知道 Scala 的集合类,但是关于我可以做些什么来完成这项工作的任何想法?或者其他使用 Scala 原生 JSON 库的建议?
采纳答案by tonek
You may try lift json, it's native scala lib: http://www.assembla.com/spaces/liftweb/wiki/JSON_Support
你可以试试lift json,它是原生的scala lib:http: //www.assembla.com/spaces/liftweb/wiki/JSON_Support
回答by dmeister
You can use a java converter:
您可以使用 java 转换器:
import scala.collection.JavaConverters._
case class MyType (val x:String, val y:List[SomeOtherType]) {
def toJson() = new Gson().toJson(this.asJava())
}
回答by om-nom-nom
Or other suggestions
Or other suggestions
spray-jsonis a lightweight, clean and efficient JSON implementation in Scala.
Spray-json是 Scala 中轻量级、干净且高效的 JSON 实现。
It sports the following features:
它具有以下功能:
- Simple immutable model of the JSON language elements
- An efficient JSON PEG parser (implemented with parboiled)
- Choice of either compact or pretty JSON-to-string printing
- Type-class based (de)serialization of custom objects (no reflection, no intrusion)
- JSON 语言元素的简单不可变模型
- 一个高效的 JSON PEG 解析器(用 parboiled 实现)
- 选择紧凑或漂亮的 JSON 到字符串打印
- 自定义对象的基于类型类(反)序列化(无反射,无入侵)
回答by Jenny
You can use Java converters in a type adapter, but it's a bit finicky:
您可以在类型适配器中使用 Java 转换器,但它有点挑剔:
case class GsonListAdapter() extends JsonSerializer[List[_]] with JsonDeserializer[List[_]] {
import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl
import scala.collection.JavaConverters._
@throws(classOf[JsonParseException])
def deserialize(jsonElement: JsonElement, t: Type, jdc: JsonDeserializationContext): List[_] = {
val p = scalaListTypeToJava(t.asInstanceOf[ParameterizedType]) // Safe casting because List is a ParameterizedType.
val javaList: java.util.List[_ <: Any] = jdc.deserialize(jsonElement, p)
javaList.asScala.toList
}
override def serialize(obj: List[_], t: Type, jdc: JsonSerializationContext): JsonElement = {
val p = scalaListTypeToJava(t.asInstanceOf[ParameterizedType]) // Safe casting because List is a ParameterizedType.
jdc.serialize(obj.asInstanceOf[List[Any]].asJava, p)
}
private def scalaListTypeToJava(t: ParameterizedType): ParameterizedType = {
ParameterizedTypeImpl.make(classOf[java.util.List[_]], t.getActualTypeArguments, null)
}
}
val gson = new GsonBuilder().registerTypeHierarchyAdapter(classOf[List[_]], new GsonListAdapter()).create()
val l1 = List("a", "c")
val stringListType = new TypeToken[List[String]] {}.getType
val json1 = gson.toJson(l1, stringListType)
println(json1) // ["a","c"]
val newL1: List[String] = gson.fromJson(json1, stringListType)
assert(l1 === newL1)
val l2 = List(1, 3)
val intListType = new TypeToken[List[Int]] {}.getType
val json2 = gson.toJson(l2, intListType)
println(json2) // [1,3]
val newL2: List[Int] = gson.fromJson(json2, intListType)
assert(l2 === newL2)
回答by Programmer Bruce
Or other suggestions
或者其他建议
The Hymansonadd-on Hymanson-module-scalaprovides some scala support, including serialization of lists.
在Hyman逊附加Hyman逊模块的Scala提供了一些斯卡拉支持,包括列表的系列化。

