【问题标题】:"Failed to invoke public scala.collection.immutable.List() with no args" using GSON“无法使用 GSON 调用没有参数的公共 scala.collection.immutable.List()”
【发布时间】: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


【解决方案1】:

How can I use Gson in Scala to serialize a List?

引用问题:“Gson 不了解 Scala 的集合类”。 This answer 展示了如何使用 GSON 将具有 Scala List 成员的类序列化为 JSON。前者是问题的根源,后者是解决方案。

【讨论】:

  • 我不是在序列化你知道的...我在反序列化
  • 鉴于这是书面交流,很容易对语气产生误解,我将在您的回复中发现我在您的回复中发现的内容,因为我们的交流方式不兼容。祝你好运,但我不会再帮你了。
  • 对不兼容表示歉意
  • @ElectricCoffee JavaConverters 具有“asScala”方法,可以朝相反的方向发展。请参阅 ScalaDoc。我不知道 Gson,所以如果没有大量毫无意义的挖掘,我无法提供准确的代码。
  • @EdStaub gson should 只是充当实例化器并根据需要输入值......但我可能错了,我看到使用 asJava 或 asScala 的问题是它可能需要我编辑每个类,在这种情况下使用数组会更容易......
猜你喜欢
  • 2019-07-28
  • 2020-11-07
  • 1970-01-01
  • 1970-01-01
  • 2013-02-26
  • 2018-08-23
  • 2017-06-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多