Skip to content

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

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

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

val json = jsonAst.prettyPrint // or .compactPrint

Convert any Scala object to a JSON AST using the toJson extension method

val jsonAst = List(1, 2, 3).toJson

Convert a JSON AST to a Scala object with the convertTo method

val myObject = jsonAst.convertTo[MyObjectType]

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
  }

See also

Favorite site