MaxG
MaxG

Reputation: 1077

Parsing a json object with a dynamic field in Kotlin

I have a JSON object:

{
  "mobileNum": "05x-xxxxxxx", 
   "appId": "some_app", 
   "messageId": "printUsersFirstTime", 
   "shouldSendDate": "2017-10-03T16:20+03:00", // this is optional 
   "paramMap": { "userName": "some_name" }, 
   "filters": { "UNIQUE": false, "RECENT": "{ \"unit\": \"MINUTE\", \"size\": 5 }"
}

I use Spring Boot and Kotlin. Spring boot automatically maps the mentioned JSON to the following model bean:

data class SmsDto(
    var mobileNum: String? = null,
    val appId: String? = null,
    val messageId: String? = null,
    var paramMap: Map<String, String>? = null,
    var shouldSendDate: Timestamp? = null,
    var filters: Map<String, String>? = defaultFilters
)

As you see, the problem I have is with filters field, which is a String, but may contain another JSON object. So I used a lazy solution of escaping the inner JSON double quotes and then parsing It by myself.

Is there a more standard solution that will allow me to send a proper inner JSON object?

Upvotes: 0

Views: 1874

Answers (1)

erkangur
erkangur

Reputation: 2128

Spring Boot appears to be using Jackson library to work with your data classes and json format. You can use another data class as type of filters field.

data class SmsDto(
    var mobileNum: String? = null,
    val appId: String? = null,
    val messageId: String? = null,
    var paramMap: Map<String, String>? = null,
    var shouldSendDate: Timestamp? = null,
    var filters: SmsFiltersDto? = defaultFilters
)

data class SmsFiltersDto(
    var yourField: Boolean = false,
    ...
)

Upvotes: 3

Related Questions