0

I am hitting an external API with request body as below

{
   "recordId1":{
      "manufacturer": "ABC",
      "modelNo": "1234",
      "requestedService": "XYZ",
      "fromCountry": "India",
      "fromCity": "Banglore"
   },
   "recordId2":{
      "manufacturer":null,
      "modelNo":"4567",
      "requestedService":null,
      "fromCountry":null,
      "fromCity":null
   }
}

I am getting JSON response as below

{
    "recordId1": {
        "manufacturer": "ABC",
        "modelNo": "1234",
        "requestedService": "XYZ",
        "fromCountry": "India",
        "fromCity": "Banglore",
        "instructions": {
            "code": "INDIA",
            "shippingInstructions": "Banglore"
        }
    }
    "recordId2": {
        "manufacturer": null,
        "modelNo": "4567",
        "requestedService": null,
        "fromCountry": null,
        "fromCity": null,
        "instructions": {
            "error": "Failed type validation {\"manufacturer\":\"Missing required field\",\"requestedService\":\"Missing required field\",\"fromCountry\":\"Missing required field\",\"fromCity\":\"Missing required field\"}"
        }
    }
}

I need to deserialize json and store it in apex map. Could anyone help me with the apex wrapper class?

0

1 Answer 1

0

First you would need to create an apex class that mimics the JSON response

public class JsonResponseDummy {

    public String manufacturer;
    public String modelNo;
    public String requestedService;
    public String fromCountry;
    public String fromCity;
    public Instructions instructions;

    public class Instructions {
        public String code;
        public String shippingInstructions;
        public String error;
    }
    
}

and then, you can try something like this:

// getting JSON response from static resource for more clarity
StaticResource sr = [SELECT Id, Body FROM StaticResource WHERE Name = 'response'];
String jsonResponse = sr.Body.toString();

Map<String, JsonResponseDummy> records = new Map<String, JsonResponseDummy>();
JSONParser parser = JSON.createParser(jsonResponse);
parser.nextToken();

while (parser.nextToken() != null) {
    if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
        String currentRecordKey = parser.getText();
        parser.nextToken();
        if (parser.getCurrentToken() == JSONToken.START_OBJECT) {
            JsonResponseDummy jrd = (JsonResponseDummy) parser.readValueAs(JsonResponseDummy.class);
            records.put(currentRecordKey, jrd);
        }        
    }
}

System.debug(records);

Hope it helps!

Not the answer you're looking for? Browse other questions tagged .