【问题标题】:Apex (Salesforce) read json from responseApex(Salesforce)从响应中读取 json
【发布时间】:2016-09-27 12:50:09
【问题描述】:

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

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

我收到状态为 200(ok) 的响应

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

这是我在 apex 中的代码(服务工作 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}

                }

我在这里错过了什么?

【问题讨论】:

标签: salesforce apex


【解决方案1】:

非常感谢。

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

 public class JsonPhone {

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

        }

对字符串稍作修改,因为它不能很好地与我的响应字符串配合使用

"{\"phoneIsValid\":true,\"IsMobile\":true,\"message\":\"成功\"}"

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

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

jPhone 准备就绪。

【讨论】:

  • 我相信字符串中的额外引号是 system.Debug 工作方式的产物,因此您不需要尝试修复它的行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-13
  • 2013-09-09
  • 1970-01-01
  • 2013-03-11
  • 2014-04-15
  • 2014-09-06
  • 1970-01-01
相关资源
最近更新 更多