skip to Main Content

So I have this domain class in a spring boot app for a REST API, that contains two subdomain objects:

public class Maximize {

   
    private Profit profit;
   
    private Stats stats;
...

The generated JSON looks like this:

{
    "profit": {
        "request_ids": [
            "id_001",
            "id_003"
        ],
        "total_profit": 88
    },
    "stats": {
        "avg_night": 10,
        "min_night": 8,
        "max_night": 12
    }
}

but I need it to look like this:

{
    "request_ids": [
        "id_001",
        "id_003"
    ],
    "total_profit": 88,
    "avg_night": 10,
    "min_night": 8,
    "max_night": 12
}

So, what I need is to void profit and stats level in json and just print its content

I tried by overriding toString() method of Maximixe class, look around Gson library but I couldn’t find an easy or simple way of doing it, any hints?

2

Answers


  1. JSON handling in Spring Boot is not like a text editor where you can simply delete lines at your will.

    You can

    • either define a different class for the target object with the structure you want (the proper way), map source to target and then serialize the target or
    • put everything into a Map<String, Object> with a List<String> for that array. The keys of the map will become the names of the properties. Then serialize the map.
    Login or Signup to reply.
  2. Depends on what library you are using. If you are using Jackson you can use the @JsonUnwrapped annotation:

    public class Maximize {
    
        @JsonUnwrapped
        private Profit profit;
        @JsonUnwrapped
        private Stats stats;
    ...
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search