Parsing json objects with oatpp when multiple json objects are defined
08:02 11 Jul 2024

I need to parse a json structure:

{
  "service": "service1",
  "backend": "backend1",
  "backendParams": {
                     "param1": "1",
                     "param2": "2"
   }
}

The small oatpp application I've written, more as a POC uses the backend parameter to call an external service passing the backendParams as a json "string", in theory it will be deserialised further down the chain.

I can't work out how to construct the dto for that type of json structure. Everything seems to be key-value pairs. I get a parsing error from oatpp, unless I only pass a single key-value pair in backendParams

My DTO definitions:

class BackendParamsDto : public oatpp::DTO {
  DTO_INIT(BackendParamsDto, DTO)
  DTO_FIELD(String, param1);
  DTO_FIELD(String, param2);
};

class BodyDto : public oatpp::DTO {
  DTO_INIT(BodyDto, DTO)

  DTO_FIELD_INFO(service) {
    info->required = true;
  }

  DTO_FIELD_INFO(backend) {
    info->required = true;
  }

  DTO_FIELD_INFO(backendParams) {
    info->required = true;
  }

  DTO_FIELD(String, service);
  DTO_FIELD(String, backend);
  DTO_FIELD(String, backendParams);
};

I tried defining backendParams as DTO_FIELD(Fields>>, backendParams); (a suggestion on StackOverflow on a similar question).

I need everything passed in backendParams to end up in a string, in json format as it will be passed to the backend system. Ideally I want to validate the key-value pairs but can't get beyond this point.

oat++