Advanced 30 min read

Parse the Response (JSON)

By the end of this lesson, you'll be able to:

  • Write a typed wrapper class matching the response contract
  • Deserialize the response body using that class
  • Return the converted amount from the service method

Prerequisites: "Handle Authentication"

A typed class matching the response contract

public class ConversionResponse {
    public Decimal convertedAmount;
    public Decimal rate;
    public String timestamp;
}

This class's fields map directly onto Lesson 1's response contract — {"convertedAmount": 123.45, "rate": 0.054, "timestamp": "..."}. Module 36's JSON.deserialize(json, MyClass.class) (the typed version, not deserializeUntyped) needs exactly this kind of matching class.

Parsing and returning the result

public Decimal convert(Decimal amountInZar, String targetCurrency) {
    HttpRequest request = new HttpRequest();
    request.setEndpoint('callout:Currency_API/convert?from=ZAR&to=' + targetCurrency + '&amount=' + amountInZar);
    request.setMethod('GET');

    HttpResponse response = new Http().send(request);

    ConversionResponse parsed = (ConversionResponse) JSON.deserialize(response.getBody(), ConversionResponse.class);
    return parsed.convertedAmount;
}

The method now genuinely does what Lesson 1's contract promised: takes an amount and a currency, calls the external API, and returns the actual converted Decimal — every earlier lesson's piece (the request, the auth, now the parsing) finally comes together into a complete, working method.

Exercise

Add a getRate() method to CurrencyConversionService that returns just the rate field from a conversion, reusing the same request/parse logic.

Show hint

Follow the same shape as convert(), returning parsed.rate instead.

APEX

Parse the Response (JSON) Quiz

1. Why does ConversionResponse's fields need to match the JSON response's field names exactly?

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

This lesson finally completes the method's core purpose — parsing the JSON response into a typed Apex class and returning the actual converted amount.