将 JSON 放入数组中

Posted

技术标签:

【中文标题】将 JSON 放入数组中【英文标题】:Put JSON in array 【发布时间】:2016-05-26 21:34:37 【问题描述】:

我有一些网络服务,我想获取 JSON 代码并放入一个数组中。

这是我的代码:

NSArray * mnewarray;
@try 
    mnewarray = [self JsonToArray:[NSString stringWithFormat:@"%@/WS_Get_APEM_Staff.php",_GV.WSpath]];


@catch ( NSException *e ) 

- (NSArray *) JsonToArray:(NSString *)mURLString
    NSURL *url = [NSURL URLWithString:[mURLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

    NSError *jsonParsingError = nil;

    NSArray *result = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableContainers error:&jsonParsingError];

    NSLog(@"Result= %@",result);

    return result;

这是我的网络服务

<?php

 $error    = ["error" => "1"];

  include "_Connect.php";

     $tsql = "SELECT *
     FROM staff";

     $stmt = sqlsrv_query( $conn, $tsql);

     if($stmt)
     
      $a=0;
          echo "[";
           while($object = sqlsrv_fetch_object($stmt))  if($a==1) echo ","; echo json_encode($object); $a=1; 
          echo "]";
          else
              echo json_encode($error);


         include "_Disconnect.php";

           ?>

这就是它发布的 Json

["employeeusername":"123","employeepassword":"123","employeename":"nnnnnnnnnnnn","employeeactive":1,"trabajador":null,"id_staff":1


  "employeeusername":"456","employeepassword":"456","employeename":"oooooooooo","employeeactive":1,"trabajador":null,"id_staff":2,

   "employeeusername":"789","employeepassword":"789","employeename":"yyyyyyyyyyy","employeeactive":1,"trabajador":null,"id_staff":3,

       "employeeusername":"ewer","employeepassword":"ewer","employeename":"xxxxxxx","employeeactive":1,"trabajador":null,"id_staff":4,

     "employeeusername":"asdfg","employeepassword":"asdfg","employeename":"asdfghj","employeeactive":1,"trabajador":null,"id_staff":5]

问题是结果返回空然后代码不运行并产生异常。请帮我解决这个问题。

【问题讨论】:

你可以发布你服务器发送的Json吗?这个问题已经在***.com/questions/12582166/… 确定编辑帖子。 1 分钟 我准备好发布请求了 您可以发布异常吗?无论如何,我看到你使用 NSString *string = dic[@"array"];并且在您的服务器响应中看不到类似数组的东西 @"NSInvalidArgumentException" - 原因:@"data parameter is nil" 问题出在 NSData *response = [NSURLConnection sendSynchronousRequest:request returnedResponse:nil error:nil]; NSError *jsonParsingError = nil; NSLog(@"Result= %@",response); NSArray *result = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableContainers error:&jsonParsingError];响应和结果不返回注意它在 null 【参考方案1】:

我终于找到了错误,NSAppTransportSecurity 的响应返回 nil 所以...我只尝试这个Transport security has blocked a cleartext HTTP

网络服务正常工作

【讨论】:

以上是关于将 JSON 放入数组中的主要内容,如果未能解决你的问题,请参考以下文章

将 JSON 放入数组

将字节数组放入 JSON,反之亦然

使用 Ajax Jquery 将 Json 结果返回的数据数组放入 DataTable 中

使用 JQuery 将 JSON 数组放入 HTML 列表

Java - 如何读取json文件并将值放入数组中

PHP POST Curl 标头,如何将数组放入数组中? [复制]