Apex(Salesforce)从回复

时间:2016-09-25 07:14:47

标签: salesforce apex

您好我的服务以格式返回json:

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

我收到状态为200的回复(确定)

但是如何在客户端Apex中从json(phoneIsValid,IsMobile,message)获取我的值。

此处我的代码位于顶点(服务工作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}

                }

我在这里缺少什么?

1 个答案:

答案 0 :(得分:0)

超级谢谢。

你需要添加为你构建的类Json pbject

 public class JsonPhone {

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

        }

对字符串进行一点修改,因为它对我的响应字符串

效果不佳
  

" {\" phoneIsValid \":真,\" IsMobile \":真,\"消息\":\& #34;成功\"}"

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

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

和jPhone准备好了。