Hey, I have an issue right now, I need to convert a jsonnode from my database to a…
- User
Hey, I have an issue right now, I need to convert a jsonnode from my database to a kotlin Map<String, Any?>. So I need first to check if the json node is an object so I can successfully migrating it to a map.
but right now it is not working since the Map::class.java is returning Map<,> and so the compiler is not okay with that. Here is my code, could you help me?
@Entity @Table( name = "generic_tracking_method", schema = SHIPMENT_TRACKING_SCHEMA, indexes = [ Index(name = "idx_tracking_platform_generic_tracking_method", columnList = "tracking_platform"), ], ) class GenericTrackingMethodJpa( @Column(name = "tracking_platform", nullable = false, length = 255, columnDefinition = "VARCHAR(255)") @Enumerated(EnumType.STRING) var trackingPlatform: TrackingPlatformJpa, @Column(name = "label", nullable = false, length = 255, columnDefinition = "VARCHAR(255)") var label: String, @JdbcTypeCode(SqlTypes.JSON) @Column(name = "config", nullable = false, columnDefinition = "TEXT") var config: JsonNode, ) { @Id @GeneratedValue(strategy = IDENTITY) var id: Int = 0
private val objectMapper = jacksonObjectMapper() fun toDomain(): GenericTrackingMethod = GenericTrackingMethodId(id).let { id -> when (trackingPlatform.toDomain()) { AFTERSHIP -> { val config1: Map<String, Any?> = config .takeIf { it.isObject } ?.let { objectMapper.treeToValue(it, Map::class.java) } ?: emptyMap() GenericTrackingMethod.Aftership(id, label, config1) } TDI -> GenericTrackingMethod.Tdi(id, label) NONE -> GenericTrackingMethod.None(id, label) } } final override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null) return false val oEffectiveClass = if (other is HibernateProxy) other.hibernateLazyInitializer.persistentClass else other.javaClass val thisEffectiveClass = if (this is HibernateProxy) this.hibernateLazyInitializer.persistentClass else this.javaClass if (thisEffectiveClass != oEffectiveClass) return false other as GenericTrackingMethodJpa return id == other.id } final override fun hashCode(): Int = if (this is HibernateProxy) this.hibernateLazyInitializer.persistentClass.hashCode() else javaClass.hashCode()}
- Assistant
To resolve the issue you're encountering, you need to help the compiler understand the exact generic types you're working with. When dealing with generics in Kotlin (and Java), type erasure can cause complications, especially when deserializing JSON into generic types like
Map<String, Any?>.In your code, you're using
objectMapper.treeToValue(it, Map::class.java), which returns a due to type erasure. This is why the compiler isn't accepting it when you try to assign it to a variable of type .