Home > OS >  Can an API response root property be removed from a Java POJO response?
Can an API response root property be removed from a Java POJO response?

Time:01-17

I have been wondering what exactly I am doing wrong here. The response I am getting from my POJO class has a root property that I am unable to remove.

I have this JSON response:

{
  "page": 1,
  "per_page": 6,
  "total": 12,
  "total_pages": 2,
  "data": [
    {
      "id": 1,
      "name": "cerulean",
      "year": 2000,
      "color": "#98B2D1",
      "pantone_value": "15-4020"
    },
    {
      "id": 2,
      "name": "fuchsia rose",
      "year": 2001,
      "color": "#C74375",
      "pantone_value": "17-2031"
    }
  ],
  "support": {
    "url": "https://reqres.in/#support-heading",
    "text": "To keep ReqRes free, contributions towards server costs are appreciated!"
  }
}

I converted JSON to these POJO classes and ignore properties not required for my test.

First POJO

  @Getter
  @Setter
  @AllArgsConstructor
  @NoArgsConstructor
  public class Datum{
  public int id;
  public String name;
  public int year;
  public String color;
  public String pantone_value;
  }

Second POJO

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class Root {

@JsonIgnore
public int page;

@JsonIgnore
public int per_page;

@JsonIgnore
public int total;

@JsonIgnore
public int total_pages;

public ArrayList<Datum> data;
@JsonIgnore
public Support support;
}

Third POJO:

    @Getter
    @Setter
    @AllArgsConstructor
    @NoArgsConstructor
    public class Support {
    public String url;
    public String text;
    }

I want to get the properties in the Responses' Data list and convert it to a map, so I did this:

public void verify( List<Map<String, String>> myTest) { //myTest holds the expected response i want to use for my assertion
    Root response = (resp.as(Root.class));
    Map<String, Object> mapResponse = mapper.convertValue(response, new TypeReference<>() {
    });

    System.out.println(mapResponse);   
  }

Output:

{data=[{id=1, name=cerulean, year=2000, color=#98B2D1, pantone_value=15-4020}, {id=2, name=fuchsia rose, year=2001, color=#C74375, pantone_value=17-2031}, {id=3, name=true red, year=2002, color=#BF1932, pantone_value=19-1664}]}

The {data= root property (key) at beginning of the output is what I was trying to remove as it's making my assertion fail.

This is the output I would like:

[{id=1, name=cerulean, year=2000, color=#98B2D1, pantone_value=15-4020}, {id=2, name=fuchsia rose, year=2001, color=#C74375, pantone_value=17-2031}]

How can I convert the response's data format to get this?

CodePudding user response:

You can convert only data list

List<Map<String, Object>> mapResponse = mapper.convertValue(response.getData(), new TypeReference<>() {
});

System.out.println(mapResponse);
  •  Tags:  
  • java
  • Related