Saturday, September 11, 2021

Scala -Java : Convert String to Json

Scala -Java : Convert String to Json 

Code (Maven / https://mvnrepository.com/artifact/com.google.code.gson/gson):

import com.google.gson.{Gson, JsonParser}
val json="""{"hello": "world", "age": 42}"""
 val parser:JsonParser= new JsonParser();
val res= parser.parse(json).getAsJsonObject()
println(res.get("hello")) // world

//read from file
//val path="/path/file.json"
//val lines = scala.io.Source.fromFile(path, "utf-8").getLines.mkString

Code 2 (Requires Lift Web - Maven):

import net.liftweb.json._
import net.liftweb.Serialiazation.write
case class Address(city:String,Country:String)
case class Person(name:String ,address:Address)
implicits def formats=DefaultFormats
print(write(Person("Sam",Address("NY","US"))

No comments:

Post a Comment