Skip to main content

{

    "operator": "rohan"

    "details": {

        "title": "example glossary",

        "hours": 744,

        "usedHours": 9.5,

        "venue": "island"

      }

}

 

This is the json which I have converted from json to apex and trying to read the values operator,title,hours,usedHours and venue.

 

I’m successfully getting the details for operator, title and venue.

 

But For hours and usedHours, it always returning 0 and 0.0, respectively whereas they have values in json. In apex, the return type for this are Integer and Double, respectively.

 

Can anybody please help me here ?

1 respuesta
  1. 26 mar 2022, 15:24

    Hey, please try the following approach:  

    String jsonString = '{"operator": "rohan","details": {"title": "example glossary","hours": 744,"usedHours": 9.5,"venue": "island"}}';

    Map<String, Object> jsonObj = (Map<String, Object>)JSON.deserializeUntyped(jsonString);

    Map<String, Object> details = (Map<String, Object>)jsonObj.get('details');

    Integer hours = (Integer)details.get('hours');

    Decimal usedHours = (Decimal)details.get('usedHours');

    System.debug('JSON object hours: ' + hours);

    System.debug('JSON object usedHours: ' + usedHours);

     

     Steps: 

     

    1. First, let's save response as a string.

    2. Then let's deserialize it (=objectify) and cast it to String-Object Map (you need object type because the value corresponding to 'details' key is in fact an object).

    3. Get reference to the details object, then deserialize it and downcast to map again.

    4. Now, grab reference to the 'hours' or 'usedHours' key in details object and cast it to Integer/Decimal.

    5. Display results or do whatever you want.

0/9000