MOCKSTACKS
EN
Questions And Answers

More Tutorials









Scala JSON

Examples

JSON with spray-json


spray-json provides an easy way to work with JSON. Using implicit formats, everything happens "behind the scenes":

Make the Library Available with SBT


To manage spray-json with SBT managed library dependencies:

libraryDependencies += "io.spray" %% "spray-json" % "1.3.2"

Note that the last parameter, the version number (1.3.2), may be different in different projects.

The spray-json library is hosted at repo.spray.io.

Import the Library


import spray.json._
import DefaultJsonProtocol._

The default JSON protocol DefaultJsonProtocol contains formats for all basic types. To provide JSON functionality for custom types, either use convenience builders for formats or write formats explicitly.

Read JSON


// generates an intermediate JSON representation (abstract syntax tree)
val res = """{ "foo": "bar" }""".parseJson // JsValue = {"foo":"bar"}
res.convertTo[Map[String, String]] // Map(foo -> bar)

Write JSON


val values = List("a", "b", "c")
values.toJson.prettyPrint // ["a", "b", "c"]


Conclusion

In this page (written and validated by ) you learned about Scala JSON . What's Next? If you are interested in completing Scala tutorial, your next topic will be learning about: Scala Macros.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.