-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWeekday.scala
85 lines (77 loc) · 2.63 KB
/
Weekday.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package example
import com.fasterxml.jackson.core.{JsonGenerator, JsonParser}
import com.fasterxml.jackson.databind.annotation.{JsonDeserialize, JsonSerialize}
import com.fasterxml.jackson.databind.{DeserializationContext, JsonDeserializer, JsonSerializer, SerializerProvider}
import com.typesafe.scalalogging.LazyLogging
@JsonSerialize(using = classOf[WeekdaySerializer])
@JsonDeserialize(using = classOf[WeekdayDeserializer])
sealed trait Weekday extends Ordered[Weekday] {
val name: String
val abbreviation: String
val order: Int
override def compare(that: Weekday): Int = this.order - that.order
}
case object Monday extends Weekday {
override val name: String = "Monday"
override val abbreviation: String = "Mo"
override val order: Int = 0
}
case object Tuesday extends Weekday {
override val name: String = "Tuesday"
override val abbreviation: String = "Tu"
override val order: Int = 1
}
case object Wednesday extends Weekday {
override val name: String = "Wednesday"
override val abbreviation: String = "We"
override val order: Int = 2
}
case object Thursday extends Weekday {
override val name: String = "Thursday"
override val abbreviation: String = "Th"
override val order: Int = 3
}
case object Friday extends Weekday {
override val name: String = "Friday"
override val abbreviation: String = "Fr"
override val order: Int = 4
}
case object Saturday extends Weekday {
override val name: String = "Saturday"
override val abbreviation: String = "Sa"
override val order: Int = 5
}
case object Sunday extends Weekday {
override val name: String = "Sunday"
override val abbreviation: String = "Su"
override val order: Int = 6
}
class WeekdaySerializer extends JsonSerializer[Weekday] {
override def serialize(
w: Weekday,
json: JsonGenerator,
provider: SerializerProvider
): Unit = {
json.writeString(w.name)
}
}
class WeekdayDeserializer extends JsonDeserializer[Weekday] with LazyLogging {
override def deserialize(p: JsonParser, ctxt: DeserializationContext): Weekday = {
import com.fasterxml.jackson.databind.JsonNode
val node: JsonNode = p.getCodec.readTree(p)
val s: String = node.asText()
logger.debug(s"s=$s")
s match {
case Monday.name => Monday
case Tuesday.name => Tuesday
case Wednesday.name => Wednesday
case Thursday.name => Thursday
case Friday.name => Friday
case Saturday.name => Saturday
case Sunday.name => Sunday
case _ => throw new IllegalArgumentException(
s"[$s] is not a valid value for Weekday"
)
}
}
}