Last active
February 12, 2019 06:32
-
-
Save satendrakumar/bbcc04f49ab9a656a6dfebaa4b080f5a to your computer and use it in GitHub Desktop.
Scala Utility class for parsing and writing Json(Write once and use everywhere )
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.json4s._ | |
import org.json4s.native.{JsonMethods, Serialization} | |
object JsonUtility { | |
implicit val formats = DefaultFormats | |
def write[T <: AnyRef](value: T): String = Serialization.write(value) | |
def parse(value: String): JValue = JsonMethods.parse(value) | |
} | |
case class Person(name: String, email: String, age: Int) | |
object JsonApp extends App { | |
import JsonUtility._ | |
/** | |
* case class to json conversion | |
*/ | |
val person: Person = Person("bob", "bob@gmail.com", 21) | |
val personJson: String = write(person) | |
println(personJson) // output => {"name":"bob","email":"bob@gmail.com","age":21} | |
/** | |
* Json to case class conversion | |
*/ | |
val jsonData = | |
"""{"name":"rob","email":"rob@gmail.com","age":25}""" | |
val personFromJson: Person = parse(jsonData).extract[Person] | |
println(personFromJson) // output => Person(rob,rob@gmail.com,25) | |
/** | |
* List of case class to json conversion | |
*/ | |
val persons = List(Person("bob", "bob@gmail.com", 21), Person("rob", "rob@gmail.com", 25), Person("joy", "joy@gmail.com", 35)) | |
val personsJson = write(persons) | |
println(personsJson) // output => [{"name":"bob","email":"bob@gmail.com","age":21},{"name":"rob","email":"rob@gmail.com","age":25},{"name":"joy","email":"joy@gmail.com","age":35}] | |
} | |
//sbt dependency | |
// "org.json4s" %% "json4s-native" % "3.5.0" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment