【问题标题】:How to encode MYSQL response in JSON and parse in iOS app如何在 JSON 中编码 MYSQL 响应并在 iOS 应用程序中解析
【发布时间】:2013-03-20 18:35:58
【问题描述】:

我的 php 有一个名为 load 的方法。我可以插入不同的方法,但是当我更改参数以与此方法对话时,我认为它可以正确发送数据,但它没有显示在我的应用程序上。

index.php

function load(){
          //Establish connection
   $con=mysqli_connect("localhost","root","","Mealidea");

    // Check connection
    if (mysqli_connect_errno()){
        $errorR['name']="Failed to connect to mysql".mysqli_connect_error();
        echo json_encode(errorR);
    }

    //Perform query
    $result = mysqli_query($con,"SELECT * FROM User");
    $myjsons = array();

    while($row = mysql_fetch_assoc($result)){ 
        $myjsons[] = $row;
    }

    //Close connection
    mysqli_close($con);    

    echo json_encode($myjsons);
}

设置请求:

//Get from DB
    NSURL*url=[NSURL URLWithString:@"http://localhost/Tutorials/index.php?f=load&key=6dM7V0n5GqYJLTMibQDf2gA2a94h8hbF"];

    //URL request
    NSURLRequest*request=[NSURLRequest requestWithURL:url];


    //Set the connection
    connection = [NSURLConnection connectionWithRequest:request delegate:self];

    if (connection) {
        webData=[[NSMutableData alloc]init];
    }

得到答案:

NSDictionary*data=[NSJSONSerialization JSONObjectWithData:webData options:0 error:&error];

    //If data is nil, then print error
    if (data==nil) {
        //NSLog(@"%@",error);
    }

    //Print the data
    NSLog(@"%@",data);

    //???? how to parse data?
    NSDictionary*num=[data valueForKey:@"User"];

【问题讨论】:

  • 您是否在询问如何让数据显示在您的应用程序中?
  • 我认为我发送和接收的内容之间存在错误。在应用程序中,我应该作为字典接收吗?这些数据是如何结构化的? (我这周刚读到 PHP)。 PHP 发送的是字典还是数组?

标签: php mysql ios json nsurlrequest


【解决方案1】:

根据这一行,您的 PHP 脚本似乎正在发送一个数组(以 JSON 编码),但您的 Objective-C 代码似乎需要一个 NSDictionary

NSDictionary*data=[NSJSONSerialization JSONObjectWithData:webData options:0 error:&error];

应该是这样

NSArray *users = [NSJSONSerialization JSONObjectWithData:webData options:0 error:&error];

然后您应该能够遍历用户的NSArray,并以UITableView 或类似的形式呈现它们。

【讨论】:

    猜你喜欢
    • 2016-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-16
    相关资源
    最近更新 更多