无法在Scala中使用GSON解析JSON

时间:2016-09-23 01:39:42

标签: scala gson

我正在使用Gson将json解析为Scala,但发生错误,代码如下,查看Gson.fromJson(String,java.lang.reflect.Type type)

object GsonUtils {
  val GSON = new GsonBuilder().create()

  def java2Json(obj: Object) = GSON.toJson(obj)

  def json2Java[T](json: String, tyze: Type) = GSON.fromJson(json, tyze)
}

case class Data(@BeanProperty val name: String, @BeanProperty val age: Int)

object GsonUtilsTest {
  def main(args: Array[String]) {
      val d = Data("1",1)
       val json = GsonUtils.java2Json(d)
      println(json)

    //ERROR
    val d2 = GsonUtils.json2Java(json, classOf[Data]).asInstanceOf[Data]

    val dats = new java.util.ArrayList[Data]()
    dats.add(Data("1",1))

    val json2 = GsonUtils.java2Json(dats)


    val tyze = new TypeToken[ java.util.List[Data]](){

    }.getType()

    //ERROR
    GsonUtils.json2Java(json2,tyze)

  }
}

当我运行它时,异常抛出,例外是:

Exception in thread "main" java.lang.ClassCastException: com.xyz.Data incompatible with scala.runtime.Nothing$
    at java.lang.ClassCastException.<init>(ClassCastException.java:58)
    at com.xyz.GsonUtils$.json2Java(GsonUtils.scala:18)
    at com.xyz.GsonUtilsTest$.main(GsonUtils.scala:30)
    at com.xyz.GsonUtilsTest.main(GsonUtils.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:88)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
    at java.lang.reflect.Method.invoke(Method.java:613)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

1 个答案:

答案 0 :(得分:0)

使用fromJson(String json,Class classOfT)而不是fromJson(String json,Type typeOfT)

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == (char)Keys.Return)
    {
        //Do Something and the select all texts to prepare text box for next card
        this.textBox1.SelectAll();
    }
}