【发布时间】:2014-04-22 00:39:00
【问题描述】:
首先是我的代码:
// Description.scala
package com.wausoft.jsonrpc.model
import com.google.gson.annotations.SerializedName
class Description {
@SerializedName("Language")
var language = ""
@SerializedName("Description")
var description = ""
}
// Item.scala
package com.wausoft.jsonrpc.model
import com.google.gson.annotations.SerializedName
class Item {
@SerializedName("Number")
var number = 0
@SerializedName("Description")
var description: List[Description] = Nil
}
// Result.scala
package com.wausoft.jsonrpc.model
import com.google.gson.annotations.SerializedName
class Result {
@SerializedName("Type")
var typeNum = 0
@SerializedName("Description")
var description: List[Description] = Nil
@SerializedName("Items")
var items: List[Item] = Nil
}
// Response.scala
package com.wausoft.jsonrpc.model
class Response {
var jsonRPC = ""
var result: List[Result] = Nil
var id = 0
}
// main file
package com.wausoft.jsonrpc
import scala.io.Source
import com.wausoft.jsonrpc.model._
import com.google.gson._
object Program {
def getJson(file: String): String = Source.fromFile(file)("UTF-8").mkString
def parseJFile(json: String): Response = new Gson().fromJson(json, classOf[Response])
// insert main method here
}
当我尝试将数据解析为 POSO 时,标题中出现错误,如果我将所有列表替换为数组,它工作正常,但困扰我的是这工作:
var lst: List[Int] = Nil
lst = List(1,2,3,4,5)
lst foreach print // produces 12345
如果上面的示例有效,为什么我的代码无效?我的意思是我基本上做同样的事情,唯一的例外是我让 Gson 处理列表制作,是因为它被包裹在一个类中,还是我错过了什么?
【问题讨论】:
-
并没有真正回答我的问题,它所暗示的只是 gson 的替代品......这不是我想要的
-
查看最后一个答案。
-
仍然没有回答我的问题
-
引用问题:“Gson 不知道 Scala 的集合类”。答案 (stackoverflow.com/a/8415907/2197460) 展示了如何使用 GSON 将具有 Scala List 成员的类序列化为 JSON。前者是问题的根源,后者是解决方案。
标签: json list scala parsing gson