0
votes

Hello i have service that return me json in format:

"{\"phoneIsValid\":true,\"IsMobile\":true,\"message\":\"success\"}"

I get response with status 200(ok)

but how can i get my values from json (phoneIsValid,IsMobile,message),in client Apex.

Here my code in apex(service working 100%)

        JSONGenerator gen = JSON.createGenerator(true);
        gen.writeStartObject();  
        gen.writeStringField('phone',  '123466789');
        gen.writeEndObject(); 
        String jsonString= gen.getAsString();

        HttpRequest req = new HttpRequest();
        req.setMethod('POST');
        req.setHeader('Content-Type', 'application/json');
        req.setHeader('Accept', 'application/json');
        req.setHeader('Content-Length',String.Valueof(jsonString.length()));
        req.setHeader('Connection','keep-alive');
        req.setHeader('Charset','utf-8');
        req.setEndpoint('https://services.ValidatePhone');
        req.setBody(jsonString);

        Http http = new Http();
        HTTPResponse res = new HTTPResponse();
        res = http.send(req);
        JSONParser parser = JSON.createParser(res.getBody());
       //res.getBody() return -->

"{\"phoneIsValid\":true,\"IsMobile\":true,\"message\":\"success\"}"

        if(res.getStatusCode() == 200)//i get 200,but cant find my value from Json
                {

                //here i need to get my values from Json
                // SOME THINK LIKE THIS
                //  if(parser.phoneIsValid==true){ MY CODE}

                }

What i missing here?

1

1 Answers

0
votes

superfell thanks.

you need to add class that buils for you Json pbject

 public class JsonPhone {

    public boolean phoneIsValid=false;
    public boolean IsMobile=false;
    public String message='empty';  

        }

a little modify of the string,because it didnt work well with my response string

"{\"phoneIsValid\":true,\"IsMobile\":true,\"message\":\"success\"}"

           String sResponseText = res.getBody();
           sResponseText=sResponseText.replaceFirst('^\"+', '');
           sResponseText=sResponseText.replaceFirst('\"+$', '');
           sResponseText=sResponseText.replace('\\', '');

           JsonPhone jPhone = (JsonPhone)JSON.deserialize(sResponseText, JsonPhone.class);

and jPhone ready fro use.