JSON编码问题ios 5

时间:2012-05-04 09:13:42

标签: iphone json ios5 encoding

好的,我应该更好地解释这个问题。 我正在开发一个用于显示数据的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”, “农布雷”: “打气\ 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”;     }    ) 就像浏览器一样......这是我的问题,因为我有一些带口音的人...

2 个答案:

答案 0 :(得分:0)

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

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

那应该解决它。

答案 1 :(得分: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"]);
}