scala 解析\n用circe分隔的json

8yparm6h  于 2023-03-30  发布在  Scala
关注(0)|答案(2)|浏览(169)

你们知道如何解析一个没有方括号的json对象数组吗

{ "jsonValue1": "val1", "jsonValue2": [1, 1, 2, 2]}
{ "jsonValue1": "val1", "jsonValue2": [1, 1, 2, 2]}
{ "jsonValue1": "val1", "jsonValue2": [1, 1, 2, 2]}

列表[MyScalaType]

case class MyScalaType(jsonValue1: String, jsonValue2: List[Int])

对这样的List的常规解析返回:错误消息正文格式错误:无效JSON

3vpjnl9f

3vpjnl9f1#

好吧,感谢Luis Miguel Mejía Suárez与“io.circe”%%“circe-fs 2”我能够解析这样的json
这里是简短的概述.我正在使用http 4s客户端

client.get(uri)(
   _.bodyText
    .through(stringStreamParser)
    .through(decoder[F, MyScalaType])
    .compile
    .toList
)
pdsfdshx

pdsfdshx2#

例如,您可以将字符串拆分为多行,并在解析之前将字符串转换为有效的JSON字符串

import io.circe.{Decoder, Json}
import io.circe.parser.{decode, parse}
import io.circe.generic.semiauto

case class MyScalaType(jsonValue1: String, jsonValue2: List[Int])
object MyScalaType {
  implicit val dec: Decoder[MyScalaType] = semiauto.deriveDecoder
}

val str =
  """
    { "jsonValue1": "val1", "jsonValue2": [1, 1, 2, 2]}
    { "jsonValue1": "val1", "jsonValue2": [1, 1, 2, 2]}
    { "jsonValue1": "val1", "jsonValue2": [1, 1, 2, 2]}
  """

val lines = str.linesIterator.filter(_.trim.nonEmpty).toList

val str1 = lines.mkString("[", ",", "]")

val res = parse(str1)
res.map(_.noSpaces)
// Right([{"jsonValue1":"val1","jsonValue2":[1,1,2,2]},{"jsonValue1":"val1","jsonValue2":[1,1,2,2]},{"jsonValue1":"val1","jsonValue2":[1,1,2,2]}])
res.flatMap(_.as[List[MyScalaType]])
// Right(List(MyScalaType(val1,List(1, 1, 2, 2)), MyScalaType(val1,List(1, 1, 2, 2)), MyScalaType(val1,List(1, 1, 2, 2))))
decode[List[MyScalaType]](str1)
// Right(List(MyScalaType(val1,List(1, 1, 2, 2)), MyScalaType(val1,List(1, 1, 2, 2)), MyScalaType(val1,List(1, 1, 2, 2))))

或者可以将字符串拆分为多行,并将每行解析为JSON

import cats.syntax.traverse._

val res = lines.traverse(parse).map(Json.arr)
res.map(_.noSpaces)
// Right([{"jsonValue1":"val1","jsonValue2":[1,1,2,2]},{"jsonValue1":"val1","jsonValue2":[1,1,2,2]},{"jsonValue1":"val1","jsonValue2":[1,1,2,2]}])
res.flatMap(_.as[List[MyScalaType]])
// Right(List(MyScalaType(val1,List(1, 1, 2, 2)), MyScalaType(val1,List(1, 1, 2, 2)), MyScalaType(val1,List(1, 1, 2, 2))))

相关问题