Mit Bezug auf folgenden Beitrag zu beantworten: Find the maximum value from JSON data in Scalakein JSON-Objekt Exception in Scala
Ich bin sehr neu in der Programmierung in Scala, und als eine Lösung Zustände in der genannten Post, teste ich folgenden Code:
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)
}
}
ich erhalte in Zeile 15. java.lang.IllegalStateException folgenden Fehler: Nicht ein JSON-Objekt:
die Inhalte der JSON-Datei sind wie folgt:
[{ "id":978,"price":2513},
{ "id":979,"price":8942},
{ "id":980,"price":1268},
{ "id":981,"price":5452},
{ "id":982,"price":5585},
{ "id":983,"price":9542}]
Nicht sicher, warum dieser Fehler angezeigt wird. Jede Hilfe wäre willkommen. Vielen Dank.
Ihre Datei enthält keinen gültigen JSON. Bitte teilen Sie den Inhalt von jsonData.txt, aber ich würde nur online nach einem JSON-Formatierer suchen, der Ihr Problem für Sie hervorhebt. –
Bearbeitete die Frage mit dem Inhalt der JSON-Datei. Ich habe GSON gesucht und versucht. – hshantanu
Ich denke, dass Ihr Code funktioniert haben könnte, wenn Sie '.getAsJsonArray' anstatt' .getAsJsonObject' verwendet hätten. –