I have a Json string, after parsing I want it to remain in decimal form.
import play.api.libs.json._
val jsonString = """{"value":2.0}"""
println(jsonString)
println(Json.parse(jsonString))
The output of the code above is:
{"value":2.0}
{"value":2}
I need it to be
{"value":2.0}
{"value":2.0}
2
Answers
play-json created an option to preserve zero decimals
https://github.com/playframework/play-json/pull/831/files
Just add
-Dplay.json.serializer.preserveZeroDecimal=true
to VM options.When you say
Json.parse(jsonString)
you get aJsValue
representing both the key "value" and the value "2.0". To get at the 2 you need to lookup the "value" key from the result:Currently the 2 is still represented in the Json library. To extract it to a native scala format you can use the
as
function on a playJsValue
:It should be noted that a number of types are difficult to represent in JSON such as decimals, dates, binary srings and regexs. If 2 and 2.0 is significant to you it may be worth reaching out and discussing with the person who generates the JSON in the first place. It may be that you need the number wrapped in quotes (to be treated like a string instead of a JsNumber).
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number