I have an API which demands the json request to be in specific array form where array object fields are accessed with names which is then posted using Retrofit. Please refer below code:
Kotlin:
class RailPoint(
var railPointId,
var startTime,
var endTime
)
var rails: ArrayList<RailPoint>()
rails.add(RailPointObject1)
rails.add(RailPointObject2)
So, after converting above rails
array to json, it should yield following result:
{
"railPoint[0][railPointId]": 5,
"railPoint[0][startTime]": "",
"railPoint[0][endTime]": "2021-10-19 07:37:19",
"railPoint[1][railPointId]": 1,
"railPoint[1][startTime]": "2021-10-19 07:33:37",
"railPoint[1][endTime]": "2021-10-19 07:35:20",
}
So, how can I achieve this type of json array form?
It's an ugly request, and you might be able to resolve it with an ugly solution :)
I wouldn't suggest this for anything serious, large, or anything that requires some hard and complex maintenance, but if this object will stay that simple (one int and two strings, non-nullable fields) and won't change a lot, you can do it manually:
class RailPoint(
var railPointId: Int,
var startTime: String,
var endTime: String
)
val rails = listOf(
RailPoint(1, "", "2021-10-19 07:37:19"),
RailPoint(2, "2021-10-19 07:33:37", "2021-10-19 07:35:20"),
)
fun toJson(rails: List<RailPoint>): String {
val sb = StringBuilder()
rails.forEachIndexed { index, railPoint ->
sb.append("\"railPoint[$index][railPointId]\": ${railPoint.railPointId},")
sb.append("\"railPoint[$index][startTime]\": \"${railPoint.startTime}\",")
sb.append("\"railPoint[$index][endTime]\": \"${railPoint.endTime}\",")
}
return "{ $sb }"
}
It is very dirty approach, but might be enough, as long as you don't make RailPoint
more complex, especially, if you don't add members that are custom classes or collections.
(I assumed that times are String
s, but if they are not, just add some date formatting in the formula)