0

I have the following json to parse:

{
"id":"123",
"nbElements":15,
"containers":[
  {
    "id":"cont1",
    "capacity":3
  }
],
"operations":[
  {
    "id":"cont1_01",
    "weight":3,
    "containerId":"cont1"
  },
  {
    "id":"cont1_02",
    "weight": 4, 
    "containerId":"cont1"
  }
]
}

Using quicktype, it suggests the following code:

import com.fasterxml.jackson.annotation.*
import com.fasterxml.jackson.core.*
import com.fasterxml.jackson.databind.*
import com.fasterxml.jackson.databind.deser.std.StdDeserializer
import com.fasterxml.jackson.databind.module.SimpleModule
import com.fasterxml.jackson.databind.node.*
import com.fasterxml.jackson.databind.ser.std.StdSerializer
import com.fasterxml.jackson.module.kotlin.*

val mapper = jacksonObjectMapper().apply {
    propertyNamingStrategy = PropertyNamingStrategy.LOWER_CAMEL_CASE
    setSerializationInclusion(JsonInclude.Include.NON_NULL)
}

data class Welcome (
    @get:JsonProperty(required=true)@field:JsonProperty(required=true)
    val id: String,

    @get:JsonProperty(required=true)@field:JsonProperty(required=true)
    val nbElements: Long,

    @get:JsonProperty(required=true)@field:JsonProperty(required=true)
    val containers: List<Container>,

    @get:JsonProperty(required=true)@field:JsonProperty(required=true)
    val items: List<Item>
) {
    fun toJson() = mapper.writeValueAsString(this)

    companion object {
        fun fromJson(json: String) = mapper.readValue<Welcome>(json)
    }
}

data class Container (
    @get:JsonProperty(required=true)@field:JsonProperty(required=true)
    val id: String,

    @get:JsonProperty(required=true)@field:JsonProperty(required=true)
    val capacity: Long
)

data class Item (
    @get:JsonProperty(required=true)@field:JsonProperty(required=true)
    val id: String,

    @get:JsonProperty(required=true)@field:JsonProperty(required=true)
    val weight: Long,

    @get:JsonProperty("containerId", required=true)@field:JsonProperty("containerId", required=true)
    val containerID: String
)

I want to store the whole container object in each item instead of the containerId but I don't want to change the json, it must be done in the code.

More generally, is there way to make the code more concise? Is there more suitable tool than jackson for example.

0 Answers0