【问题标题】:How to parse jsonData?如何解析jsonData?
【发布时间】:2016-06-06 06:06:19
【问题描述】:

您好,我正在使用 ResponseData 响应变得很好但是当我解析时它显示 nil.first 这是我的响应

{
"type": "1",
"item": "Order created successfully.",
"order_id": "7"
} 
{
"multicast_id": 9215180185089775977,
"success": 1,
"failure": 0,
"canonical_ids": 0,
"results": [{
    "message_id": "0:1465191236656122%86acb02ff9fd7ecd"
  }]
}

这是我的代码

NSData * urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];


            NSLog(@"Response code: %ld", (long)[response statusCode]);

            NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
            NSLog(@"Response ==> %@", responseData);

            if (urlData)
            {
          jsonData=[[NSDictionary alloc] init];
              jsonData = [NSJSONSerialization
                            JSONObjectWithData:urlData
                            options:NSJSONReadingMutableLeaves
                            error:nil];

如何解析这种响应?

【问题讨论】:

  • 出现什么样的问题?
  • jsonData 显示 Nil。但是 responseData 高于响应。
  • 是的,我也试过了
  • 谢谢,但在场景中我无法解析 jsonData。

标签: ios objective-c json nsdictionary


【解决方案1】:

你的 json 不正确

{
"type": "1",
"item": "Order created successfully.",
"order_id": "7"
} 
{
"multicast_id": 9215180185089775977,
"success": 1,
"failure": 0,
"canonical_ids": 0,
"results": [{
    "message_id": "0:1465191236656122%86acb02ff9fd7ecd"
  }]
}

例如,您忘记了逗号/标签或关闭/打开括号不正确。尝试使用这个:

 {
    "type": "1",
    "item": "Order created successfully.",
    "order_id": "7",

    "multicast_id": 9215180185089775977,
    "success": 1,
    "failure": 0,
    "canonical_ids": 0,
    "results": [{
        "message_id": "0:1465191236656122%86acb02ff9fd7ecd"
      }]
    }

【讨论】:

    【解决方案2】:

    使用 nsurlconnection 获取 jsonData。 你需要 nsurlrequest 来生成请求和 nsurlconnection 来建立连接。一旦你建立连接。有一些代表 nsurlconnectiondelegate 可以用来获取 json 数据。之后你很容易解析数据

    【讨论】:

    • 但是上面代码中的问题是什么,其他 URL 使用相同的代码可以正常工作。
    • 我认为你应该双引号所有的键和值,而不是显示 nil 值。试试吧...
    • 对不起,如果你不介意我没有理解任何示例代码
    【解决方案3】:

    http://jsonlint.com/ 上查看您的回复。这表明您的响应是否有效。

    JSON 响应应该是单个 NSDictionaryNSArray。但是您有两个字典

    要以编程方式检查您的响应是否有效,请使用:-

    NSError *error;
    if ([NSJSONSerialization JSONObjectWithData:data
                                        options:kNilOptions
                                          error:&error] == nil)
    {
        // Handle error
    }
    

    如果有效,您可以继续进行转换。

    【讨论】:

      猜你喜欢
      • 2018-02-13
      • 2012-10-17
      • 2018-11-24
      • 2019-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多