Reputation: 7419
I am trying to write a JSON API using Scala & Play Framework. My application needs to respond to a request in JSON format, converting a list of products to JSON
I'm implementing a writes
method on my Product class which converts the fields to JSON. Every value needs to be converted to js using a method like JsString
Here 'tis
def writes(product: Product) = {
JsObject(Seq(
"id" -> JsNumber(product.id),
"title" -> JsString(product.title),
"description" -> JsString(product.description),
"available_online" -> JsBoolean(product.available_online)
))
}
This code is failing in the third line because of a type mismatch
[error] found : Integer
[error] required: BigDecimal
But when I consult the documentation, there seems to be no type for an integer.
So how should I deal with a field like id
in JSON ?
Upvotes: 2
Views: 214
Reputation: 97331
JSON does not distinguish between integer and floating point types, that's why you only see the JsNumber(value: BigDecimal)
method in the documentation. You would have to convert your Integer
to BigDecimal
first using the BigDecimal
object:
def writes(product: Product) = {
JsObject(Seq(
"id" -> JsNumber(BigDecimal(product.id)),
"title" -> JsString(product.title),
"description" -> JsString(product.description),
"available_online" -> JsBoolean(product.available_online)
))
}
Upvotes: 5