doujia5863 2019-07-01 16:45
浏览 258

将JSON中的数组作为数组或字符串返回到二维数组

Using an API (which I am writing) I need to return a fairly simple array from a server running PHP using JSON for use in Objective-C.

On the phone, the code will be added to an array of the following form:

NSArray *carPics =@[@[@"ford",@"ford.png"],@[@"bmw",@"bmw.png"];

I can return the above in JSON as a string by escaping all the special characters--a bit tedious but possible, or replacing the special characters with magic strings like ***. and then make the string as an array using :

NSArray *arr = [str componentsSeparatedByString:@"***"];

On the other hand, I could create an array in PHP and return the array to the phone which would then have to convert the array to Objective-C.

$carpics = array(
  array(
    "ford" => "ford.png",
    "bmw" => "bmw.png",
  );

The downside of this is it would involve more conversions.

Is either approach better or are they six of one, half a dozen of the other?

Edit

Currently the JSON sent by server looks like this:

{"carpics":{"ford":"ford.png","bmw":"bmw.png"}}

I am trying to decode it on phone using:

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


        NSMutableArray *carPics = [[json objectForKey:@"carpics"]mutableCopy];
NSArray *myArray = carPics;

This works fine. I have verified that json is a dictionary. Unfortunately, I have also verified using kindOfClass that carpics or myArray is not an array as I want but a dictionary too.

If I try to grab the first element of myArray using:

 NSArray *object = myArray[i];

I get an error:

[__NSDictionaryM objectAtIndexedSubscript:]: unrecognized selector sent to instance 0x174449420'

I really want an array as I wish to go through each element of the array in order one at a time.

What do I need to do for my JSON to be a proper array of arrays. I can either change the JSON coming from the server or process the JSON differently on the phone.

Here is the PHP code that creates the JSON:

header("Content-Type: application/json");
$ret = array("ford"=>"ford.png","bmw"=>"bmw.png");
echo json_encode(array('carpics'=>$ret));
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
    • ¥15 C# datagridview 单元格显示进度及值
    • ¥15 thinkphp6配合social login单点登录问题
    • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
    • ¥15 如何在scanpy上做差异基因和通路富集?
    • ¥20 关于#硬件工程#的问题,请各位专家解答!
    • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
    • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
    • ¥30 虚心请教几个问题,小生先有礼了
    • ¥30 截图中的mathematics程序转换成matlab