So I am planning to create the following JSON file in Kotlin:
{"Basket A": {"Row 1":"Apple", "Row 2":"Orange", "Row 3":"Pear", "Row 4":"Grapes"}}
{"Basket B": {"Row 1":"Mango", "Row 2":"Pineapple", "Row 3":"Kiwi", "Row 4":"Cherry"}}
{"Basket C": {"Row 1":"Banana", "Row 2":"Papaya", "Row 3":"Watermelon", "Row 4":"Strawberry"}}
{"Basket D": {"Row 1":"Avocado", "Row 2":"Peach", "Row 3":"Lemon", "Row 4":"Guava"}}
currently I am using the following code:
val rows = mapOf(
"Row 1" to "Apple",
"Row 2":"Orange",
"Row 3":"Pear",
"Row 4":"Grapes"
)
val basketA = mapOf(
"Basket A" to rows
)
Then I can convert it to JSON by using Gson() function as follows:
val gson = Gson()
val geoJsonString = gson.toJson(basketA)
All is fine if there is only 1 basket or 1 row in the JSON file, but how about basket B, C, and D? How to insert a new line in the JSON file?
Thank you if you can share any insights.
2
Answers
This is not valid json
If you want to include these objects as they are in a json object you would need to be in an array like so
The important things to note here are that the individual rows are comma separated inside a pair of square braces
[]
with abaskets
key and everything is wrapped inside an outer pair of braces{}
.It shouldn’t be too hard to adjust your code to produce the above result
As mentioned in one of the answer, the json that you’re expecting is not properly formatted. To create the desired and correct JSON structure with multiple baskets, you can create a
Map
for each basket and then combine them into a singleMap
. Something like: