1
package org.json4s.native
3
import org.specs2.mutable.Specification
5
import org.json4s.native.Serialization.{read, write => swrite}
6
import org.json4s.native
7
import java.util.{GregorianCalendar, Date}
8
import java.sql.Timestamp
10
class MapSerializationExamples extends Specification {
11
implicit val formats = native.Serialization.formats(NoTypeHints)
13
"Map with Symbol key" in {
14
val pw = Map[Symbol, String]('a -> "hello", 'b -> "world")
16
ser must_== """{"a":"hello","b":"world"}"""
17
read[Map[Symbol, String]](ser) must_== pw
20
"Map with Int key" in {
21
val pw = Map[Int, String](1 -> "hello", 2 -> "world")
23
ser must_== """{"1":"hello","2":"world"}"""
24
read[Map[Int, String]](ser) must_== pw
27
"Map with Long key" in {
28
val pw = Map[Long, String](1l -> "hello", 2l -> "world")
30
ser must_== """{"1":"hello","2":"world"}"""
31
read[Map[Long, String]](ser) must_== pw
34
"Map with Date key" in {
35
//months are zero indexed
36
val gc = new GregorianCalendar(2013, 0, 1)
37
val d2013 = gc.getTime
39
val d2014 = gc.getTime
40
val pw = Map[Date, String](d2013 -> "hello", d2014 -> "world")
42
val f2013 = formats.dateFormat.format(d2013)
43
val f2014 = formats.dateFormat.format(d2014)
44
ser must_== """{"""" + f2013 + """":"hello","""" + f2014 + """":"world"}"""
45
read[Map[Date, String]](ser) must_== pw
48
"Map with Timestamp key" in {
49
val t2013 = new Timestamp(1356998400)
50
val t2014 = new Timestamp(1388534400)
51
val pw = Map[Timestamp, String](t2013 -> "hello", t2014 -> "world")
54
val f2013 = formats.dateFormat.format(t2013)
55
val f2014 = formats.dateFormat.format(t2014)
56
ser must_== """{"""" + f2013 + """":"hello","""" + f2014 + """":"world"}"""
57
read[Map[Timestamp, String]](ser) must_== pw
60
"Map with custom key and no custom serializer -- should suggest CustomKeySerializer implementation" in {
61
val pw = Map[KeyWithInt, String](KeyWithInt(1) -> "hello", KeyWithInt(2) -> "world")
62
val thrown = swrite(pw) must throwA[MappingException]
63
thrown.message must contain("Consider implementing a CustomKeySerializer")
64
thrown.message must contain("KeyWithInt")
67
"Map with custom key and custom key serializer" in {
68
val serializer = new CustomKeySerializer[KeyWithInt](format => (
69
{ case s: String => KeyWithInt(s.toInt)},
70
{ case k: KeyWithInt => k.id.toString }
72
implicit val formats = native.Serialization.formats(NoTypeHints) + serializer
74
val pw = Map[KeyWithInt, String](KeyWithInt(1) -> "hello", KeyWithInt(2) -> "world")
76
ser must_== """{"1":"hello","2":"world"}"""
77
read[Map[KeyWithInt, String]](ser) must_== pw
80
"case class with custom map" in {
81
val pw = PlayerWithCustomMap("zortan", Map("2013" -> "zortan13", "2014" -> "zortan14"))
83
val s: String = """{"name":"zortan","aliasByYear":{"2013":"zortan13","2014":"zortan14"}}"""
85
val deser = read[PlayerWithCustomMap](ser)
90
case class KeyWithInt(id: Int)
92
case class PlayerWithCustomMap(name: String, aliasByYear: Map[String, String])