从Scala中的JSON数据中查找最大值

从Scala中的JSON数据中查找最大值,json,scala,parsing,Json,Scala,Parsing,我对Scala编程非常陌生。我正在编写一个测试程序,从JSON数据中获取最大值。我有以下代码: 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"

我对Scala编程非常陌生。我正在编写一个测试程序,从JSON数据中获取最大值。我有以下代码:

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}  

    }
}
json_arr.foreach{println}打印以下数据:

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

我被困在如何从这些JSON数据中找到最高价格的问题上?也就是说,在这种情况下,输出应该是“8999”

尽管Play JSON很方便,但您也可以使用正则表达式

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

尽管Play JSON很方便,但您也可以使用正则表达式

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)
   }
})
我还建议使用或播放JSON

但是你可以不使用任何这样的库

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
我还建议使用或播放JSON

但是你可以不使用任何这样的库

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

您可以尝试以下方式:

    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)
    }
}
package com.nielsen.buy.integration.commons
导入collection.immutable.IndexedSeq
导入com.google.gson.gson
导入com.google.gson.JsonObject
导入com.google.gson.JsonParser
案例类包装器对象(val json_字符串:数组[MyJsonObject])
案例类MyJsonObject(val id:Int,val price:Int)
对象演示{
val gson=新gson()
def main(参数:数组[字符串])={
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对象:wrapperObject=gson.fromJson(jsonStringAsObject,classOf[wrapperObject])
var maxPrice:Int=0
对于(i最大价格)
{
maxPrice=i.price
}
println(最大价格)
}
}

检查它是否有助于您

您可以尝试以下方法:

    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)
    }
}
package com.nielsen.buy.integration.commons
导入collection.immutable.IndexedSeq
导入com.google.gson.gson
导入com.google.gson.JsonObject
导入com.google.gson.JsonParser
案例类包装器对象(val json_字符串:数组[MyJsonObject])
案例类MyJsonObject(val id:Int,val price:Int)
对象演示{
val gson=新gson()
def main(参数:数组[字符串])={
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对象:wrapperObject=gson.fromJson(jsonStringAsObject,classOf[wrapperObject])
var maxPrice:Int=0
对于(i最大价格)
{
maxPrice=i.price
}
println(最大价格)
}
}

检查它是否有助于您查看或查看其他Json解析库。@maasg谢谢。播放JSON似乎很有帮助。@maasg有其他方法吗?我不需要任何额外的库。请看一看或其他Json解析库。@maasg谢谢。播放JSON似乎很有帮助。@maasg有其他方法吗?我不需要任何额外的库。这个解决方案很有效,而且很好。但是,我希望使用Play JSON或其他JSON解析来完成它。@hshantanu绝对如此!:)这个解决方案是有效的。但是,我希望使用Play JSON或其他JSON解析来完成它。@hshantanu绝对如此!:)我试着运行代码。但是案例类MyJsonObject{val id,val price}似乎有一些问题。。不幸的是,我无法编译和粘贴。。您可以使用下面的代码并尝试一次,它工作正常。您必须使用下面的maven依赖项信息为gson和json api准备JAR:com.google.code.gson gson 2.5并在下面的代码中运行,让我来了解任何问题:@A srinivas:代码工作正常,但您已经为字符串插入了硬编码值。这不是很有效。我需要它来工作。因此,我可以将您的答案标记为正确,并对其进行投票。我刚刚编辑了代码,取消了上面一行的注释,并对硬代码字符串进行了注释。它现在应该可以正常工作了,已经说过您的json应该是您文件中的有效json。thanksI试图运行代码。但是案例类MyJsonObject{val id,val price}似乎有一些问题。。不幸的是,我无法编译和粘贴。。您可以使用下面的代码并尝试一次,它工作正常。您必须使用下面的maven依赖项信息为gson和json api准备JAR:com.google.code.gson gson 2.5并在下面的代码中运行,让我来了解任何问题:@A srinivas:代码工作正常,但您已经为字符串插入了硬编码值。这不是很有效。我需要它来工作。因此,我可以将您的答案标记为正确,并对其进行投票。我刚刚编辑了代码,取消了上面一行的注释,并对硬代码字符串进行了注释。它现在应该可以正常工作了,已经说过您的json应该是您文件中的有效json。谢谢