In Scala I want to create a JSON Object or JSON String where the result would be something similar to this (i.e. a relatively basic nested JSON):
{
"info":{
"info1":"1234",
"info2":"123456",
"info3":false
},
"x":[
{
"x1_info":10,
"x2_info":"abcde"
}
],
"y":[
{
"y1_info":"28732",
"y2_info":"defghi",
"y3_info":"1261",
"y_extra_info":[
{
"Id":"543890",
"ye1":"asdfg",
"ye2":"BOOLEAN",
"ye3":false,
"ye4":true,
"ye5":true,
"ye6":0,
"ye7":396387
}
]
}
]
}
I plan to use this object in tests so ideally I can set the information inside the JSON object to whatever I want (I don't plan on sourcing the info for the JSON object from a separate file). I tried the following where I created a Map of the information I want in my JSON object and then tried converting it to json using gson:
val myInfo = Map(
"info" -> Map("info1" -> "1234",
"info2" -> "123456",
"info3" -> "false"),
"x" -> Map("x1_info" -> 10,
"x2_info" -> "abcde"),
"y" -> Map("y1_info" -> "28732",
"y2_info" -> "defghi",
"y3_info" -> "1261",
"y_extra_info"-> Map("Id" -> "543890",
"ye1" -> "asdfg",
"ye2" -> "BOOLEAN",
"ye3" -> false,
"ye4" -> true,
"ye5" -> true,
"ye6" -> 0,
"ye7" -> 396387
)
)
)
val gson = new GsonBuilder().setPrettyPrinting.create
print(gson.toJson(myInfo))
However though it produces JSON correctly does not produce the JSON in the structure I have above but instead structures it like so:
{
"key1": "info",
"value1": {
"key1": "info1",
"value1": "1234",
"key2": "info2",
"value2": "123456",
...(etc)...
I have figured out an inelegant way of achieving what I want by creating a string containing the JSON I expect and then parsing as JSON (but I assume there is a better way)
val jsonString = "{\"info\":{\"info1\":\"1234\", \"info2\":\"123456\", " +
"\"info3\":false}," +
"\"x\":[{ \"x1_info\":10,\"x2_info\":\"abcde\"}]," +
"\"y\":[{\"y1_info\":\"28732\",\"y2_info\":\"defghi\",\"y3_info\":\"1261\", " +
"\"y_extra_info\":[{" +
"\"Id\":\"543890\",\"ye1\":\"asdfg\"," +
"\"ye2\":\"BOOLEAN\",\"ye3\":false,\"ye4\":true," +
"\"ye5\":true,\"ye6\":0,\"ye7\":396387}]}]}"
I'm relatively new to Scala so perhaps using a Map or writing it all out as a string is not the best or most "Scala way"?
Is there an easy way to create such a JSON object using preferable either gson or spray or otherwise by some other means?