Phani
Phani

Reputation: 13

Scala - Parsing a nested json array

I have a json string like below, please suggest what changes should be done to my code in order to parse this json into a case class in Scala?

    {
        "boundaries": [
          [
            [
              -11110372.022426892,
              4676428.402837045
            ],
            [
              -11124418.538414171,
              4740594.245854561
            ],
            [
              -11101812.444140816,
              4744556.315065523
            ],
            [
              -11087326.99540134,
              4684866.726958438
            ],
            [
              -11108506.41908069,
              4677271.949698344
            ],
            [
              -11110152.500391051,
              4676569.01290604
            ],
            [
              -11110372.022426892,
              4676428.402837045
            ]
          ]
        ]
      }

I have tried the below code, but it doesnt work


import org.json4s._
import org.json4s.JsonDSL._
import org.json4s.JsonAST._
import org.json4s.jackson.JsonMethods._

val jsonString = """<the string given above>"""
val jsonAst: JValue = parse(jsonString)

case class Boundaries(r : Array[Array[Array[Array[Double]]]])

How to associate this case class to the json string and get all the numerical values in this class?

Upvotes: 0

Views: 1204

Answers (1)

Ashalynd
Ashalynd

Reputation: 12573

This worked for me:

import org.json4s.jackson.JsonMethods._
import org.json4s._
import org.json4s.JsonDSL._
import org.json4s.JsonAST._
import org.json4s.jackson.JsonMethods._

implicit val formats = DefaultFormats

case class Boundaries (boundaries: List[List[List[Double]]])

val jsonString = """
 <your json>
"""

scala> val jsonAst: JValue = parse(jsonString)
jsonAst: org.json4s.JsonAST.JValue = <parsed JValue>

scala> jsonAst.extract[Boundaries]
res0: Boundaries = Boundaries(List(List(List(-1.1110372022426892E7, 4676428.402837045), List(-1.1124418538414171E7, 4740594.245854561), List(-1.1101812444140816E7, 4744556.315065523), List(-1.108732699540134E7, 4684866.726958438), List(-1.110850641908069E7, 4677271.949698344), List(-1.1110152500391051E7, 4676569.01290604), List(-1.1110372022426892E7, 4676428.402837045))))

Upvotes: 2

Related Questions