#Check what type of class went from JSON

1 messages · Page 1 of 1 (latest)

long eagle
#

It's possible to check what type of object comes from json in easy way?

public void updateProduct(@RequestParam(name = "id") Long id, @RequestBody JsonDto jsonDto) {
        JsonMapper jsonMapper = new JsonMapper();
        Product product = jsonMapper.toEntity(jsonDto);
        System.out.println(product);
}


public record JsonDto(String type, ChairDto chairDto, BedDto bedDto) {}


public class JsonMapper {

    private final ChairMapper chairMapper;
    private final BedMapper BedMapper;

    public Product toEntity(JsonDto json) {
        switch (json.type()) {
            case "CHAIR":
                return chairMapper.toEntity(json.chairDto());
            case "BED":
                return bedMapper.toEntity(json.bedDto());
        }
        return null;
    }
}

Product is parent class for Chair and Bed. It's any simplier way to do it? I have to give api information that coming type of Dto is chairDto. Can @RequestBody get something else to automatically check it's chair or any other product?

{
  "type": CHAIR,
  "chairDto": {
    "weight": 5,
    "color": "red
  }
}

Why im trying to change it? Because while i post above JSON im getting in api something like this:

{
  "type": CHAIR,
  "chairDto": {
    "weight": 5,
    "color": "red
  },
  "bedDto": null
}

When i would add more furnitures, more dtos, more models inheritanced from Product class. The json would look like this:

{
  "type": CHAIR,
  "chairDto": {
    "weight": 5,
    "color": "red
  },
  "bedDto": null,
  "otherFurnitureDto": null,
  "andOtherDto": null,
  "nextDto": null
}

Any ideas?

short pumiceBOT
#

<@&987246883653156906> please have a look, thanks.