简体   繁体   中英

How to parse Json in scala

I want to know how to parse JSON

I am trying to parse json in scala.

But I do not know how to parse

Is there any better way?

key is numbered sequentially from 1

I use circe library...

Thanks

{
  "1": {
    "name": "hoge",
    "num": "60"
  },
  "2": {
    "name": "huga",
    "num": "100"
  },
  "3": {
    "name": "hogehuga",
    "num": "10"
  },
}

Assuming you have a string like this (note that I've removed the trailing comma, which is not valid JSON):

val doc = """
{
  "1": {
    "name": "hoge",
    "num": "60"
  },
  "2": {
    "name": "huga",
    "num": "100"
  },
  "3": {
    "name": "hogehuga",
    "num": "10"
  }
}
"""

You can parse it with circe like this (assuming you've added the circe-jawn module to your build configuration):

scala> io.circe.jawn.parse(doc)
res1: Either[io.circe.ParsingFailure,io.circe.Json] =
Right({
  "1" : {
    "name" : "hoge",
    "num" : "60"
  },
  "2" : {
    "name" : "huga",
    "num" : "100"
  },
  "3" : {
    "name" : "hogehuga",
    "num" : "10"
  }
})

In circe (and some other JSON libraries), the word "parse" is used to refer to transforming strings into a JSON representation (in this case io.circe.Json ). It's likely you want something else, like a map to case classes. In circe this kind of transformation to non-JSON-related Scala types is called decoding, and might look like this:

scala> import io.circe.generic.auto._
import io.circe.generic.auto._

scala> case class Item(name: String, num: Int)
defined class Item

scala> io.circe.jawn.decode[Map[Int, Item]](doc)
res2: Either[io.circe.Error,Map[Int,Item]] = Right(Map(1 -> Item(hoge,60), 2 -> Item(huga,100), 3 -> Item(hogehuga,10)))

You can of course decode this JSON into many different Scala representations—if this doesn't work for you please expand your question and I'll update the answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM