https://kotlinlang.org logo
#getting-started
Title
# getting-started
a

Aminu Babayo Shehu

01/30/2023, 1:05 PM
{\"customerId\":\"123\",\"id\":\"registration\",\"value\":0,\"balance\":0,\"expirationDate\":1675122800125}
Please how to convert the above string to this Promotion object
Copy code
sealed class Promotion(customerId: String, id: String, value: BigDecimal, balance: BigDecimal, expirationDate: Timestamp)
s

Sam

01/30/2023, 1:09 PM
Looks like a JSON string, so you could use something like #serialization or #jackson-kotlin to deserialize it to an object.
a

Aminu Babayo Shehu

01/30/2023, 1:10 PM
can i use fasterxml?
s

Sam

01/30/2023, 1:12 PM
The #jackson-kotlin module is an extension for the FasterXML Jackson library to enable it to work better with Kotlin classes. Yes, you could use it for this.
a

Aminu Babayo Shehu

01/30/2023, 1:12 PM
okay thank you, let me try
Do you is the method?
Copy code
val promotions = jacksonObjectMapper().readValue(promotion, Promotion::class.java)
s

Sam

01/30/2023, 1:17 PM
👍 that should work. You might need to make your class a
data
class instead of a
sealed
class, though.
a

Aminu Babayo Shehu

01/30/2023, 1:21 PM
and also
@Serializable
right?
s

Sam

01/30/2023, 1:24 PM
You don’t need that annotation if you’re using Jackson. That would only be needed if you choose to use Kotlin #serialization instead.
a

Aminu Babayo Shehu

01/30/2023, 1:24 PM
ohk, thank you Sir
🐕 1
Please what do you think if the string is in this format
{{\"customerId\":\"123\",\"id\":\"registration\",\"value\":0,\"balance\":0,\"expirationDate\":1675086187278}, {\"customerId\":\"124\",\"id\":\"registration\",\"value\":0,\"balance\":0,\"expirationDate\":1675086187278}}
s

Sam

01/30/2023, 2:13 PM
That looks a bit odd. It seems like a list containing two objects, but a JSON list is supposed to be in square brackets
[]
, not braces
{}
. If you had a valid JSON list, you could do
jacksonObjectMapper().readValue<List<Promotion>>(promotions)
. If your list really does have braces instead of square brackets, it’s not valid JSON and you would need to fix it before passing it to a JSON deserializer.
a

Aminu Babayo Shehu

01/30/2023, 2:17 PM
ohk, thank you Sir
5 Views