Last active
August 11, 2017 06:20
-
-
Save kentac55/85e92a933bcd1460dd527f692072752c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import JsonType._ | |
| import scala.collection.immutable.ListMap | |
| sealed trait JsonType { | |
| override def toString: String = { | |
| this match { | |
| case x: JsonObj if x.values == Nil => "{}" | |
| case x: JsonObj => s"{${x.values.foldLeft("")((z, n) => z + "\"" + n._1 + "\":" + n._2 + ",").dropRight(1)}}" | |
| case x: JsonArray if x.values == Nil => "[]" | |
| case x: JsonArray => s"[${x.values.foldLeft("")((z, n) => z + n.toString + ",").dropRight(1)}]" | |
| case x: JsonString => "\"" + x.value + "\"" | |
| case x: JsonNumber => x.value.toString | |
| case x: JsonBool => x.value.toString | |
| case _: JsonNull => "null" | |
| } | |
| } | |
| } | |
| object JsonType { | |
| final case class JsonObj(values: (String, JsonType)*) extends JsonType | |
| final case class JsonArray(values: JsonType*) extends JsonType | |
| final case class JsonString(value: String) extends JsonType | |
| final case class JsonNumber(value: Double) extends JsonType | |
| final case class JsonBool(value: Boolean) extends JsonType | |
| final case class JsonNull() extends JsonType | |
| def apply(value: (String, JsonType)*) = JsonObj(value:_*) | |
| def apply(value: JsonType*) = JsonArray(value:_*) | |
| def apply(value: String) = JsonString(value) | |
| def apply(value: Double) = JsonNumber(value) | |
| def apply(value: Boolean) = JsonBool(value) | |
| def apply() = JsonNull() | |
| implicit class ImplExtender[T](v: T) { | |
| def toJson: JsonType = v match { | |
| case x: String => JsonString(x) | |
| case x: Double => JsonNumber(x) | |
| case x: Boolean => JsonBool(x) | |
| case x: Seq[T] => JsonArray(x.map(_.toJson):_*) | |
| case x: ListMap[T, T] => JsonObj(x.toList.map(kv => (kv._1.toString, kv._2.toJson)):_*) | |
| case null => JsonNull() | |
| case _ => throw new ClassCastException | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment