-1

好的,我应该更好地解释这个问题。我正在开发一个 iPhone 应用程序来显示数据。数据是使用 php 文件从 Mysql 数据库中获取的。

在这里,我展示了 PHP 文件的代码:

<?php
header("text/html; charset=utf-8");
//Credenciales de la BBDD
$db = "json";
$host = 'localhost';
$username = "dpbataller";
$password = '1234';

//Conectamos al servidor de la Base de datos
$link = mysql_connect($host,$username,$password) or die("No se puede conectar");
//Seleccionamos la BBDD
mysql_select_db($db) or die ("No se ha podido seleccionar a la base de datos");
mysql_set_charset('utf8', $link);
//Lanzamos la consulta
$consulta = mysql_query("SELECT id,nombre from personas");
//Creamos un array para almacenar los resultados
$filas = array();
//Agregamos las filas devueltas al array
while ($r = mysql_fetch_assoc($consulta)) { 
$filas[] = $r;      
}
//Devolvemos el resultado
echo json_encode($filas);
?>

此时,如果我在浏览器上运行脚本,他会返回 [{"id":"0","nombre":"Pep\u00e9"}]

此外,在 xcode 项目中,我编写了以下代码:

NSString *urlString = [NSString stringWithFormat:@"http://10.0.1.18/mysql_iphone/mostrar_personas.php"];

NSURL *url = [NSURL URLWithString:urlString];

NSData *data = [NSData dataWithContentsOfURL:url];

NSError *error;

NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(@"%@", json);

控制台返回: ( { id = 0; nombre = "Pep\U00e9"; } ) 就像浏览器一样...这是我的问题,因为我有很多有口音的人...

4

2 回答 2

0

好吧,我猜你的问题是你的 JSON 不起作用,你需要使用 NSDictionary 而不是 NSArray:

    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

那应该解决它。

于 2012-05-04T09:28:35.377 回答
0

您的 JSON 看起来很笨重,实际上它完全错误。它应该看起来更像这样:

[{
    "id":1,
    "name":"Jos \u00e9"
},
{
    "id":2,
    "name":"David"
}
]

我建议您使用众多验证器之一检查 JSON 格式,例如:http: //json.parser.online.fr/

编辑 看来你被调试器愚弄了......

我尝试了以下方法:

    NSError *error = nil;
    NSData *data = [@"[{\"id\":\"0\",\"nombre\":\"Pep\u00e9\"}]" dataUsingEncoding:NSUTF8StringEncoding];

    NSArray *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
    NSLog(@"%@", json);

    NSDictionary *item = [json lastObject];
    NSString *nombre = [item objectForKey:@"nombre"];

    NSLog(@"%@", nombre);

第一个 NSLog 将打印出转义字符,但提取的字符串实际上已正确编码为 UTF8。

编辑 2

你的代码已经在工作了,你不需要改变任何东西

NSString *urlString = [NSString stringWithFormat:@"http://10.0.1.18/mysql_iphone/mostrar_personas.php"];

NSURL *url = [NSURL URLWithString:urlString];

NSData *data = [NSData dataWithContentsOfURL:url];

NSError *error;

NSArray *items = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

// This will print all the names of people in your JSON.
for (NSDictionary *item in items)
{
    NSLog(@"nombre: %@", [item objectForKey:objectForKey:@"nombre"]);
}
于 2012-05-04T09:47:52.310 回答