我尝试使用play.api.libs.json创建一个json对象。我遇到了两个编译错误。我尝试了几种方法,但我找不到任何解决办法。
这是编译错误
没有可用的Array [models.Graphs.piechartdata]的隐式格式。
从stdout读取:隐式val piec = Json.writes [piechart] 隐式val piec = Json.writes [piechart]从stdout读取:^
找不到类型models.Graphs.piechart的Json序列化程序。尝试 为此类型实现隐式Writes或Format。阅读 stdout:println(Json.toJson(p).toString) println(Json.toJson(p).toString)从stdout读取:^
这是我的代码
package models.Graphs
import play.api.Play.current
import play.api.libs.json._
import scala.language.postfixOps
import scala.collection.mutable.ArrayBuffer
case class piechart(element:String,data:Array[piechartdata])
case class piechartdata(label:String,value:Int)
object GraphsModel{
implicit val piec = Json.writes[piechart]
implicit val piecdata = Json.writes[piechartdata]
def createPieChart()={
var ar = ArrayBuffer[piechartdata]()
ar += piechartdata("Download Sales",12)
ar += piechartdata("In-Store Sales",30)
var arr:Array[piechartdata]=ar.toArray
var p=piechart("donut-example",arr)
println(Json.toJson(p).toString)
}
}
实际上我需要创建以下json对象
{element:' donut-example',data:[{label:" Download Sales",value:12},{label:" In-商店销售",价值:30}]}
答案 0 :(得分:0)
我解决了这个问题,我添加了以下几行
implicit val implicitpiecdata = new Writes[piechartdata] {
def writes(q: piechartdata): JsValue = {
Json.obj(
"label" -> q.label,
"value" -> q.value
)
}
}
implicit val implicitQuoteWrites = new Writes[piechart] {
def writes(q: piechart): JsValue = {
Json.obj(
"element" -> q.element,
"data" -> q.data
)
}
}
除了
implicit val piec = Json.writes[piechart]
implicit val piecdata = Json.writes[piechartdata]