【问题标题】:Not a JSON Object Exception in Scala不是 Scala 中的 JSON 对象异常
【发布时间】:2017-04-22 18:55:38
【问题描述】:

参考以下帖子中的答案:Find the maximum value from JSON data in Scala

我对 Scala 编程非常陌生,正如上述帖子中的一个解决方案所述,我正在测试以下代码:

import collection.immutable.IndexedSeq
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.google.gson.JsonParser

case class wrapperObject(val json_string: Array[MyJsonObject])
case class MyJsonObject(val id:Int ,val price:Int)

object Demo {

    val gson = new Gson()
    def main(args: Array[String])={
    val json_string = scala.io.Source.fromFile("jsonData.txt").getLines.mkString
    //val json_string= """{"json_string":[{"id":1,"price":4629},{"id":2,"price":7126},{"id":3,"price":8862},{"id":4,"price":8999},{"id":5,"price":1095}]}"""
    val jsonStringAsObject= new JsonParser().parse(json_string).getAsJsonObject
    val objectThatYouCanPlayWith:wrapperObject = gson.fromJson(jsonStringAsObject, classOf[wrapperObject])
    var maxPrice:Int = 0
    for(i <- objectThatYouCanPlayWith.json_string if i.price>maxPrice) 
    {
        maxPrice=  i.price
    }
    println(maxPrice)
}
}

我在第 15 行收到以下错误。java.lang.IllegalStateException: Not a JSON Object:

JSON文件内容如下:

[{ "id":978,"price":2513},
{ "id":979,"price":8942},
{ "id":980,"price":1268},
{ "id":981,"price":5452},
{ "id":982,"price":5585},
{ "id":983,"price":9542}]

不确定为什么会出现此错误。任何帮助,将不胜感激。谢谢。

【问题讨论】:

  • 您的文件不包含有效的 json。请分享 jsonData.txt 的内容,但我只会在网上搜索一个 json 格式化程序,它将为您突出显示您的问题。
  • 用 JSON 文件的内容编辑了问题。我已经搜索并尝试使用 GSON。
  • 我认为如果您使用 .getAsJsonArray 而不是 .getAsJsonObject,您的代码可能会起作用

标签: java json scala parsing


【解决方案1】:

您的 JSON 文件不是有效的 JSON 格式。根据您使用wrapperObject 实现的逻辑,您的文件应如下所示:

{
    "json_string": [
        { "id":978,"price":2513},
        { "id":979,"price":8942},
        { "id":980,"price":1268},
        { "id":981,"price":5452},
        { "id":982,"price":5585},
        { "id":983,"price":9542}
    ]
}

然后将给出输出9542。请注意,您注释掉的 json_string 版本实际上是有效的,输出将是 8999

JSON 格式是一个属性-值对,但您的文件只有值 - 即 Array[MyJsonObject]。根据您的 wrapperObject 案例类,json_string 是属性,Gson 需要将数据解析为 wrapperObject 类型的对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-28
    • 2017-03-24
    • 1970-01-01
    • 2011-12-06
    • 2013-12-01
    • 1970-01-01
    相关资源
    最近更新 更多