2016-12-04 4 views
0

Ich bin sehr neu in der Programmierung in Scala. Ich schreibe ein Testprogramm, um maximalen Wert aus JSON-Daten zu erhalten. Ich habe folgenden Code:Finde den maximalen Wert von JSON Daten in Scala

import scala.io.Source 
import scala.util.parsing.json._ 

object jsonParsing{ 

//Id int `json:"id"` 
//Price int `json:"price"` 

def main(args: Array[String]): Unit = { 

    val file_name = "jsonData.txt" 

    val json_string = scala.io.Source.fromFile("jsonData.txt").getLines.mkString 

    val json_arr = json_string.split(",") 

    json_arr.foreach {println} 

    } 
} 

Die json_arr.foreach {println} druckt folgende Daten:

[{ "id":1 
"price":4629} 
{ "id":2 
"price":7126} 
{ "id":3 
"price":8862} 
{ "id":4 
"price":8999} 
{ "id":5 
"price":1095}] 

ich im Teil steckte, herauszufinden, wie man den maximalen Preis zu finden, von solchen JSON-Daten? Das heißt, in diesem Fall sollte die Ausgabe '8999' sein.

+1

Werfen Sie einen Blick auf [playJson] (https://www.playframework.com/documentation/ 2.5.x/ScalaJson) oder andere Json-Parsing-Bibliotheken. – maasg

+0

@ maasg Danke. Play JSON scheint hilfreich zu sein. – hshantanu

+0

@ maasg Gibt es einen alternativen Weg? Wo ich keine zusätzlichen Bibliotheken benötige. – hshantanu

Antwort

1

können Sie so etwas wie dies unten probieren:

package com.nielsen.buy.integration.commons 

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) 
    } 
} 

überprüfen, ob es hilft Ihnen

+0

Ich habe versucht, den Code auszuführen. Aber es scheint ein Problem mit der Fallklasse MyJsonObject {val id, val price} zu geben – hshantanu

+0

Sorry Buddy .. leider habe ich kompiliert und eingefügt .. Sie können den unten stehenden Code nehmen und es einmal versuchen, es funktioniert gut.Sie ​​müssen Gläser bereit machen für Gson und json api Verwendung maven Abhängigkeitsinformation unter: –

+0

\t \t \t com.google.code.gson \t \t \t Gson \t \t \t 2,5 \t \t und unter Code ausführen, lassen Sie mich für alle Probleme: –

0

Obwohl Play JSON praktisch ist, können Sie auch Regex verwenden.

import scala.io.Source 
import scala.util.matching.Regex._ 

val jsonString = Source 
    .fromFile("jsonData.txt") 
    .getLines.mkString.split(",") 

var maxPrice = 0 
jsonString.foreach(each => { 
    val price: Option[Match] = ("\"price\":(\\d+)").r.findFirstMatchIn(each) 
    if (price.isDefined) { 
     maxPrice = Math.max(maxPrice, price.get.group(1).toInt) 
    } 
}) 
+0

Diese Lösung funktioniert und ist gut. Allerdings hätte ich es gerne mit Play JSON oder einem anderen JSON Parsing gemacht. – hshantanu

+0

@hshantanu Absolut! :) – NaHeon

1

Ich empfehle auch Json4s oder playJson zu verwenden.

Aber Sie könnten auf keine Bibliotheken als solche verzichten.

val json = """[{"id":1,"price":100},{"id":2, "price": 200}]""" 
val priceRegex = """"price"\s*:\s*(\d+)""".r 

val maxPrice = priceRegex.findAllIn(json).map({ 
    case priceRegex(price) => price.toInt 
}).max 
println(maxPrice) // print 200 
Verwandte Themen