Putting JSON into an Array

夙愿已清 提交于 2019-11-27 08:40:51

问题


I'm a noob when it comes to requests and JSON. Inside my app I send to the server and get back stuff so I can use it of course. I tried looking up different things but none really seem to be what I'm looking for. So I'm getting back what seems to be formatted JSON. What I want to know how to do is put it into a NSMutable array. The way I get this JSON is by using AFNetworking's AFJSONRequestOperation.

My response looks like this.

{
    id = 38;
    name = "St. Martin Hall";
},
    {
    id = 40;
    name = "Assumptions Commons";
},
    {
    id = 41;
    name = "Vickroy Hall";
},
    {
    id = 42;
    name = "St. Ann Hall";
},
    {
    id = 37;
    name = "Duquesne Towers";
}

回答1:


if your JSON format like {"mainKey":[{},{},...]}

 NSError* error;
    NSDictionary* json = [NSJSONSerialization 
        JSONObjectWithData:responseData //1
         options:kNilOptions 
        error:&error];

    NSArray* dataArray = [json objectForKey:@"mainKey"]; //2

else your JSON format like [{},{},...]

NSError* error;
    NSArray* dataArray = [NSJSONSerialization 
        JSONObjectWithData:responseData //1
        options:kNilOptions 
        error:&error];

I think your format is case 2: [] Array of Object {}

Tutorial: http://www.raywenderlich.com/5492/working-with-json-in-ios-5

JSON:http://www.json.org




回答2:


You use the NSJSONSerialization class to convert JSON to Foundation objects and convert Foundation objects to JSON.

This class is available in iOS 5.0+. If you're targetting older iOS version, have a look at a third-party JSON framework:

Comparison of JSON Parser for Objective-C (JSON Framework, YAJL, TouchJSON, etc)




回答3:


If that's what you're getting back it's not JSON I'm afraid. It does look like Javascript in a way but it should be more like

[
  {
     "id" : 38,
     "name" : "St. Martin Hall"
  },
  {
     "id" : 39,
     "name" : "Assumptions Commons"
  }
]


来源:https://stackoverflow.com/questions/15180036/putting-json-into-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!