function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
George Laird 29George Laird 29 

Help with simple JSON results

Hello.  I am getting a very simple JSON response back but can't seem to deseralize it correctly to get the ID that I need.  The response looks like this:

{
    "duration": 0.024,
    "success": true,
    "error_message": null,
    "status_code": 201,
    "payload": {
        "id": "XXXXXXXXXXXXXXX",
        "name": "test4204201112"
    }
}


My apex looks like this:

 if(res.getStatusCode() < 300){
            Type resultType = Type.forName('ResponseModel'); 
            ResponseModel r1 = (ResponseModel)JSON.deserialize(responseJSON1, ResponseModel.class);      

         }
        
    }
    

    public class ResponseModel{
        
        public decimal duration;
        public boolean success;
        public string error_message;
        public integer status_code;
        public string payload;
        public list<string> id;
        public list<string> Name;
     
    }



Of course this doesn't work.  I think the whole list thing is wrong.  Since payload is a JSON object, I'm having trouble getting that ID out of it.  All I need is that ID.  Can anyone help and change my code so that it works?  

I've also tried making another class for payload and deseralize it again to there, but no luck. 

 
Best Answer chosen by George Laird 29
Suraj PSuraj P
public class PayloadModel{
      public string name;
      public string id;
}

public class ResponseModel{
        
        public decimal duration;
        public boolean success;
        public string error_message;
        public integer status_code;
        public PayloadModel payload;
     
    }

Redefine your classes as shown above. The deserialization should work

All Answers

Suraj PSuraj P
public class PayloadModel{
      public string name;
      public string id;
}

public class ResponseModel{
        
        public decimal duration;
        public boolean success;
        public string error_message;
        public integer status_code;
        public PayloadModel payload;
     
    }

Redefine your classes as shown above. The deserialization should work
This was selected as the best answer
George Laird 29George Laird 29
@suraj P, thanks so much!  Worked great.