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条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥20 西门子S7-Graph,S7-300,梯形图
    • ¥50 用易语言http 访问不了网页
    • ¥50 safari浏览器fetch提交数据后数据丢失问题
    • ¥15 matlab不知道怎么改,求解答!!
    • ¥15 永磁直线电机的电流环pi调不出来
    • ¥15 用stata实现聚类的代码
    • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
    • ¥20 docker里部署springboot项目,访问不到扬声器
    • ¥15 netty整合springboot之后自动重连失效
    • ¥15 悬赏!微信开发者工具报错,求帮改