[SalesForce] How to convert json into Content-Type: application/x-www-form-urlencoded

For ex if I have json as:

{"attributes": {"first_name":"A","last_name":"c","email":"te@gmail.com","Id":"003S000000vz81JIAQ"}}

then how can I convert this into application/x-www-form-urlencoded format in Apex.
like this:

'id=5&first_name=a&last_name=c&email=te@gmail.com'

I have tried with EncodingUtil.urlEncode(String,'UTF-8'); method but its not converting into that format.

Best Answer

As mentioned in comment, you have to deserialize the JSON and create the EncodeURL string from it.

class Attribute {
    public String first_name{get;set;}
    public String last_name{get;set;}
    public String email{get;set;}
    public String Id{get;set;}

    public String getEncodedURL()
    {
        String encodedURL = 'id='+((null != this.id)?this.id:'')
                              +'&first_name='+((null != this.first_name)?this.first_name:'')
                              +'&last_name='+((null != this.last_name)?this.last_name:'')
                              +'&email='+((null != this.email)?this.email:'');
        return encodedURL;
    }
}

class Result {
    public Attribute attributes {get;set;}
}

String jsonStr = '{"attributes": {"first_name":"A","last_name":"c","email":"te@gmail.com","Id":"003S000000vz81JIAQ"}}';

Result rs = (Result)JSON.deserializeStrict(jsonStr, Result.class);
System.debug('JSON ##'+jsonStr);
System.debug('RESULT ##'+rs);
System.debug('EncodeURL ##'+rs.attributes.getEncodedURL());