Home > Back-end >  Scala - How to handle the Non string values ( Date, Double, Boolean) while building Json by looping
Scala - How to handle the Non string values ( Date, Double, Boolean) while building Json by looping

Time:10-21

Scala - How to handle the Non string values ( Date, Double, Boolean)in building Json by looping with Map and Object Array

in the below example I am always ending up having non string values as string. in Values Array

import play.api.libs.json._
import java.time.Instant
import scala.util.Random

val Name:Array[String] = Array("Tester1","Tester2","Tester3")
val Typeids:Array[String] = Array("00000000-0000-0000-0000-000000000302","00000000-0000-0000-0000-000000003272","00000000-0000-0000-0000-000000006272")
val values:Array[Any] = Array(1264.3,java.time.LocalDate.now,"For Testing")

  val i = 0
  val data1 = (i to 2)
    .map { r =>
      Json.toJson(Map(
        "Name" -> Json.toJson(s"${Name(r%Name.length)}"),
        "typeId" -> Json.toJson(s"${Random.shuffle(Typeids.toList).head}"),
        "value" -> Json.toJson(s"${values(r%values.length)}")))    }


val data2 = Json.toJson(data1)
println(data2)

Result :

[{"Name":"Tester1","typeId":"00000000-0000-0000-0000-000000006272","value":"1264.3"},{"Name":"Tester2","typeId":"00000000-0000-0000-0000-000000000302","value":"2022-10-19"}, {"Name":"Tester3","typeId":"00000000-0000-0000-0000-000000006272","value":"For Testing"}]

Expected result :

[{"Name":"Tester1","typeId":"00000000-0000-0000-0000-000000006272","value":1264.3},{"Name":"Tester2","typeId":"00000000-0000-0000-0000-000000000302","value":2022-10-19},{"Name":"Tester3","typeId":"00000000-0000-0000-0000-000000006272","value":"For Testing"}]

Please suggest a solution with an example, any method to achieve the expected result will be helpful to handle non-string

CodePudding user response:

You could use a helper method like,

def toJson(a: Any): JsValue = a match {
  case d: Double => Json.toJson(d)
  case i: Instant => Json.toJson(i.toEpochMilli)
  case o => Json.toJson(s"$o")
}

and use it as "value" -> toJson(values(r % values.length))

  • Related