How to avoid too many classes in jackson Java?

Viewed 147

I have JSON serialization and deserialization is done using Jackson in java. I have so many JSON fields that to serialize and deserialize I have multiple single-member classes, is there any better way to do this?

I don't have any limitations on using Jackson library, that is the library I have used for most of my cases.

public class Data{
    public String type;
    public int id;
    public Attributes attributes;
    public Relationships relationships;
}

public class Category{
    public Data data;
}

public class Service{
    public Data data;
}

public class Priority{
    public Data data;
}

public class Status{
    public Data data;
}

public class User{
    public Data data;
}

public class Relationships{
    public Category category;
    public Service service;
    public Priority priority;
    public Status status;
    public User user;
}

public class Root{
    public Data data;
}

My sample JSON for which I am serializing looks like below.

{
  "data": {
    "id": 111,
    "type": "op type",
    "attributes": {
      "title": "Some title"
    },
    "relationships": {
      "category": {
        "data": {
          "type": "category",
          "id": 1
        }
      },
      "service": {
        "data": {
          "type": "service",
          "id": 3
        }
      },
      "priority": {
        "data": {
          "type": "priority",
          "id": 1
        }
      },
      "status": {
        "data": {
          "type": "status",
          "id": 3
        }
      },
      "user": {
        "data": {
          "type": "user",
          "id": 3
        }
      }
    }
  }
}
1 Answers

Because Category, Service and others have the same fields data, if you create class manually, you can just create one common class DataWrapper. But I also see you said you use jsonschema2pojo rather than create class manually.

public class Data{
    public String type;
    public int id;
    public Attributes attributes;
    public Relationships relationships;
}

public class DataWrapper {
    public Data data;
}

public class Relationships{

    public DataWrapper category;
    public DataWrapper service;
    public DataWrapper priority;
    public DataWrapper status;
    public DataWrapper user;
}

public class Root{
    public Data data;
}
Related