上代码
import play.api.libs.json.{Json, JsValue, Writes}
/**
* Created by DGA on 2016/3/31.
*/
case class Bar(x:String,y:Int) {}
object Bar{
implicit val implicitBarWrites = new Writes[Bar]{
override def writes(testJson: Bar): JsValue = {
Json.obj(
"x" -> testJson.x,
"y" -> testJson.y
)
}
}
}
case class Foo(id: String, bar: Bar)
object TestJson{
implicit val fooWrites = Json.writes[Foo]
def main(args: Array[String]) {
println(
Json.prettyPrint(Json.toJson(Bar("x",1)))
)
println(
Json.prettyPrint(Json.toJson(Foo("foo",Bar("x",1))))
)
}
}
测试结果
{
"x" : "x",
"y" : 1
}
{
"id" : "foo",
"bar" : {
"x" : "x",
"y" : 1
}
}
隐式转换 将对象转换为json格式的字符串, Json.writes用起来更简洁