1

I need to generate a data class at run time based on my REST API response with the given class name , and need to access it .Here is the sample json response and expected sample data class .

1) Sample JSON RESPONSE

  "total": 123,
  "currentCount": 10,
  "items": [
    {
      "id": 5265194,
      "name": "Sample",
      "type": "Simple",
      
    }
  ]
}

2)Expected Data Class

data class Sample(
    @JsonProperty("currentCount")
    var currentCount: Int = 0,
    @JsonProperty("items")
    var items: List<Item> = listOf(),
    @JsonProperty("total")
    var total: Int = 0
) {
   data class Item(
        @JsonProperty("id")
        var id: Int = 0,
        @JsonProperty("name")
        var name: String = "",
        @JsonProperty("type")
        var type: String = ""
    )
}
General Grievance
  • 4,555
  • 31
  • 31
  • 45
  • 1
    It is not actually trivial, but possible using some byte-code manipulation library like [ASM](https://www.baeldung.com/java-asm) – Victor Gubin Aug 04 '21 at 10:17
  • 1
    You need to provide a schema for the response inorder to actually be able to make use of the POJO you are generating, also if you are generating it at runtime you won't be able to use it unless you compile the generated dto.. I wouldn't recommend doing this as it'll create unnecessary complications for you, there are many libraries that can generate POJOs from [JSON schema](https://json-schema.org/) , and libraries that generate JSON-schema from JSON, I think you should checkout [GraphQL](https://graphql.org/) – SaleemKhair Aug 04 '21 at 10:28

0 Answers0