【问题标题】:parse.com httpresponse return json not textparse.com httpresponse 返回 json 而不是文本
【发布时间】:2015-10-17 04:12:31
【问题描述】:

出于某种奇怪的原因,我似乎无法遍历我的 cloudcode 函数返回的结果。我认为这是因为它返回的是 json 格式的文本而不是实际的 json?如何将 httpResponse 值解析为 json 以供以后使用?
我试过使用

response.success(JSON.parse(httpResponse.text)); // and httpResponse.data

Parse.com CloudCode

 Parse.Cloud.define("test", function(request, response) {
        return Parse.Cloud.httpRequest({
            url: 'https://api.spotify.com/v1/search?q=the+eagles&type=artist&limit=1'

        }).then(function(httpResponse) {
            response.success(httpResponse.text);


        }, 
        function (error) {
            response.error("Error: " + error.code + " " + error.message);
        });
    });

Swift 代码

PFCloud.callFunctionInBackground("test", withParameters: ["" : ""]) { (result: AnyObject?, error: NSError?) in
        let json = JSON(result!); //SwiftyJSON
        print(json["artist"]) //returns null
        //print(json[0])//returns null
        //print(json) 
}

示例 JSON

{
artists: {
href: "https://api.spotify.com/v1/search?query=the+eagles&offset=0&limit=1&type=artist",
items: [
{
genres: [
"country rock",
"mellow gold",
"soft rock"
],
href: "https://api.spotify.com/v1/artists/0ECwFtbIWEVNwjlrfc6xoL",
id: "0ECwFtbIWEVNwjlrfc6xoL",
images: [
{
height: 668,
url: "https://i.scdn.co/image/173519085c3eb8301fbeb744b0b92b6747938ab3",
width: 1000
}
]

}
}

【问题讨论】:

  • 您发布的示例 json 不是有效的 json。您在所有键周围都缺少"",例如artists -> "artists" 等。您还缺少文件中最后一个} 之前的]}
  • 你可以通过这个网站来验证它是否是有效的json:jsoneditoronline.org
  • 已编辑 Json 示例以节省一些空间

标签: json xcode swift parse-platform


【解决方案1】:

您需要返回 httpResponse.data 而不是 httpResponse.text,因为您的响应对象中的内容类型是 application/json

【讨论】:

  • 当我这样做时,控制台返回一个未捕获的语法错误。 JSON.parse(httpResponse.text) 允许我查看整个 json 数据,但我无法访问其中的字段
  • 尝试解析使用 SwiftyJSON 接收的 json 时。让 json = JSON(结果!);
  • 那么 httpResponse.data 已经为你解析好了。尝试访问结果对象而不尝试使用 Swifty 解析它
  • 使用 httpResponse.data 而不是 httpResponse.text 为我做了。然后,您可以将响应对象转换为 NSDictionary,这样就很好了。
猜你喜欢
  • 2016-04-20
  • 2021-03-23
  • 1970-01-01
  • 2019-10-13
  • 2019-06-12
  • 2016-08-08
  • 2020-06-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多