Spray-json
A lightweight, clean and simple JSON implementation in Scala
Installation
spray-json is available from maven central.
If you use SBT you can include spray-json in your project with
Usage
spray-json is really easy to use. Just bring all relevant elements in scope with
import spray.json._
import DefaultJsonProtocol._ // if you don't supply your own Protocol (see below)
and do one or more of the following:
1. Parse a JSON string into its Abstract Syntax Tree (AST) representation
val source = """{ "some": "JSON source" }"""
val jsonAst = source.parseJson // or JsonParser(source)
2. Print a JSON AST back to a String using either the CompactPrinter
or the PrettyPrinter
Convert any Scala object to a JSON AST using the toJson
extension method
Convert a JSON AST to a Scala object with the convertTo
method
In order to make steps 3 and 4 work for an object of type T
you need to bring implicit values in scope that provide JsonFormat[T]
instances for T
and all types used by T
(directly or indirectly). The way you normally do this is via a "JsonProtocol".
JsObject의 Null 데이터 제거 방법
// Remove null values from JSON (could pimp onto JsValue if you wanted)
def withoutNull(json: JsValue): JsValue = json match {
case JsObject(fields) =>
JsObject(fields.flatMap {
case (_, JsNull) => None // could match on specific field name here
case other @ (name,value) => Some(other) // consider recursing on the value for nested objects
})
case other => other
}