【发布时间】: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,您的代码可能会起作用