Home > Back-end >  Do I need to create new class for every object that retrieve from API in Spring boot
Do I need to create new class for every object that retrieve from API in Spring boot

Time:08-24

Do I need to create new class for JSON object that I retrieve from an API. For example now I am using google ReCAPTCHA API and JSON that it returns looks like this:

{
  "success": false,
  "error-codes": [
    "missing-input-secret"
  ]
}

I know that when you create POST endpoint and you need to get object from request's body you should create dedicated class which is practical because you created endpoint to get this data in the first place but when I call externall API I don't want to create aditional class for each API that I call(since what I need from it is just boolean), is there any way to just get success property or do I need to create new class.
My current implementation:

final String url = "https://www.google.com/recaptcha/api/siteverify?secret={secret}&response={site}";

Map<String, Object> urlvariables = new HashMap<>();

urlvariables.put("secret", env.getProperty("captcha.secret.key"));
urlvariables.put("site", registerInfo.getCaptcha());

RestTemplate restTemplate = new RestTemplate();
String consumeJSONString = restTemplate.getForObject(url, uselessclass, urlvariables);

CodePudding user response:

Jackson also supports mapping to Map or to its own JsonNode structur.

So you could write something like this:

JsonNode node = restTemplate.getForObject(url, ObjectNode.class, urlvariables);
boolean success = node.get("success").asBoolean();
  • Related