1

I consume a web service that return one of its fields as a String, but this field is a actually a object, such as below:

{
    "message": "OK",
    "code": 1,
    "supplierPayload": "{\"field01\":\"value01\",\"field02\":\"field02\"}"
}

Is it possible anyway to parse the supplierPayload json field returned as a String into the SupplierPayload object I need in the RestTemplate call?

I would have:

this.restTemplate.getForEntity(url, MyObject.class);

And MyObject would be

public class MyObject {

    private String message;
    private int code;
    private SupplierPayload supplierPayload;

    // gets and sets
}

instead of

public class MyObject {

    private String message;
    private int code;
    private String supplierPayload;

    // gets and sets
}

This will prevent me to have an instance of ObjectMapper Spring bean anywhere I need to use this field and convert it manually handling the nest checked exceptions that ObjectMapper brings in its methods.

Philippe Gioseffi
  • 1,488
  • 3
  • 24
  • 41
  • Prefer changing the service to return a json object. Failing that, call `Map supplierPayloadMap = new ObjectMapper().readValue(myObject.getSupplierPayload(), HashMap.class)`. – Bohemian Aug 24 '22 at 01:15
  • I am not the developer of the other web service. The solution you provided is actually what I am trying to avoid, write the ObjectMapper conversion to MyObject in various places of my code. – Philippe Gioseffi Aug 24 '22 at 01:31
  • You could create a custom Jackson annotation that processes the string into an object. – Igor Flakiewicz Aug 24 '22 at 09:58
  • Could you, please, provide an example answer? Thanks for your comment. – Philippe Gioseffi Aug 24 '22 at 10:34

0 Answers0