java - Scala 中不是 JSON 对象异常

标签 java json scala parsing

引用以下帖子中的回答: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 文件不是有效的 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 需要将数据解析为 类型的对象包装对象

关于java - Scala 中不是 JSON 对象异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41024104/

相关文章:

java - 如何修复 GWT 中的 "Cookie set without httpOnly"安全问题

javascript - Vim 显示不带任何引号的 json 文件

scala - 使用高级类型的通用约束映射?

使用 val 的 Scala 构造函数与序列化框架不能很好地配合

javascript html 对象模型和模板引擎

scala - 覆盖成员和惰性 val

java - 如何在我的 Java 应用程序中显示 map 数据(最好使用 OpenStreetMaps)?

java - 根据项目版本使用发布或快照存储库进行手动部署

java - maprlogin java.lang.UnsatisfiedLinkError com.mapr.security.JNISecurity.SetParsingDone()

javascript - 无法使用 php 正确读取 JSON 文件