alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Play Framework/Scala example source code file (JavaJsonSpec.scala)

This example Play Framework source code file (JavaJsonSpec.scala) is included in my "Source Code Warehouse" project. The intent of this project is to help you more easily find Play Framework (and Scala) source code examples by using tags.

All credit for the original source code belongs to Play Framework; I'm just trying to make examples easier to find. (For my Scala work, see my Scala examples and tutorials.)

Play Framework tags/keywords

javajsonspec, json, jsonscope, lib, library, objectmapper, play, play framework, scope, specification, utf-8

The JavaJsonSpec.scala Play Framework example source code

package play.libs

import org.specs2.mutable.Specification
import org.specs2.specification.Scope

import com.fasterxml.jackson.databind.ObjectMapper

class JavaJsonSpec extends Specification {
  sequential

  private class JsonScope(val mapper: ObjectMapper = new ObjectMapper()) extends Scope {
    val testJsonString =
      """{
        |  "foo" : "bar",
        |  "bar" : "baz",
        |  "a" : 2.5,
        |  "copyright" : "\u00a9",
        |  "baz" : [ 1, 2, 3 ]
        |}""".stripMargin

    val testJson = mapper.createObjectNode()
    testJson
      .put("foo", "bar")
      .put("bar", "baz")
      .put("a", 2.5)
      .put("copyright", "\u00a9") // copyright symbol
      .put("baz", mapper.createArrayNode().add(1).add(2).add(3))

    Json.setObjectMapper(mapper)
  }

  "Json" should {
    "use the correct object mapper" in new JsonScope {
      Json.mapper() must_== mapper
    }
    "parse" in {
      "from string" in new JsonScope {
        Json.parse(testJsonString) must_== testJson
      }
      "from UTF-8 byte array" in new JsonScope {
        Json.parse(testJsonString.getBytes("UTF-8")) must_== testJson
      }
    }
    "stringify" in {
      "stringify" in new JsonScope {
        Json.stringify(testJson) must_== Json.stringify(Json.parse(testJsonString))
      }
      "asciiStringify" in new JsonScope {
        val resultString = Json.stringify(Json.parse(testJsonString)).replace("\u00a9", "\\u00A9")
        Json.asciiStringify(testJson) must_== resultString
      }
      "prettyPrint" in new JsonScope {
        Json.prettyPrint(testJson) must_== testJsonString
      }
    }
  }
}

Other Play Framework source code examples

Here is a short list of links related to this Play Framework JavaJsonSpec.scala source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.