2016-12-07 3 views
0

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.

+0

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. –

+0

Bearbeitete die Frage mit dem Inhalt der JSON-Datei. Ich habe GSON gesucht und versucht. – hshantanu

+0

Ich denke, dass Ihr Code funktioniert haben könnte, wenn Sie '.getAsJsonArray' anstatt' .getAsJsonObject' verwendet hätten. –

Antwort

1

Ihre JSON-Datei ist kein gültiges JSON-Format. Gemäß der Logik, die Sie mit wrapperObject implementiert, sollten Sie Ihre Datei wie folgt aussehen:

{ 
    "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} 
    ] 
} 

, die dann die Ausgabe 9542 geben wird. Beachten Sie, dass Ihre auskommentierte Version von json_string tatsächlich gültig ist und die Ausgabe 8999 wäre.

JSON-Format ist ein Attribut-Wert-Paar, aber Ihre Datei hat nur Wert - das ist Array[MyJsonObject]. Gemäß Ihrer wrapperObject Fallklasse ist json_string das Attribut, und es wird für Gson benötigt, um die Daten in ein Objekt vom Typ wrapperObject zu analysieren.

+0

Vielen Dank, es funktioniert. – hshantanu

Verwandte Themen