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 = ""
    )
}
2
  • 1
    It is not actually trivial, but possible using some byte-code manipulation library like ASM Commented Aug 4, 2021 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 , and libraries that generate JSON-schema from JSON, I think you should checkout GraphQL Commented Aug 4, 2021 at 10:28

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.