1

I have a class that should map some JSON data from several queries. The responses are very similar and only one of the property names change. For example one response could look like this:

{
  "data": {
    "Discipline": [
      {
        "Description": "Header",
        "Code": "32"
      }
    ]

And another like this:

{
  "data": {
    "System": [
      {
        "Description": "Basic system",
        "Code": "8653"
        
      }
    ]

So as you can see only "Discipline" and "System" changes. So I would like to use the same class to receive the data from all these different types of queries since they are so similar. So what I was thinking was a class like this:

@Data
public class QueryResponse {
    private QueryData data;

    @Data
    public static class QueryData {
        @JsonProperty(**THIS SHOULD BE DYNAMIC**)
        private Collection<Data> Data;

        @Data
        public static class Data{
            @JsonProperty("Code")
            private String Code;

            @JsonProperty("Description")
            private String Description;
        }
    }
}

However I don't know how to make the top level JsonProperty dynamic. My first thought was to pass the property name in a constructor like this:

@Data
public class QueryResponse {

    private String tableName;

    public QueryResponse(String tableName){
        this.tableName = tableName;
    }

    private QueryData data;

    @Data
    public static class QueryData {
        @JsonProperty(String.format("%s", tableName))
        private Collection<Data> Data;

        @Data
        public static class Data{
            @JsonProperty("Code")
            private String Code;

            @JsonProperty("Description")
            private String Description;
        }
    }

However that gave me the error Non-static field 'tableName' cannot be referenced from a static context, and if I make the classes non-static it says Attribute value must be constant. Any ideas how I can make this happen?

PalBo
  • 2,203
  • 3
  • 22
  • 43

0 Answers0