ios 如何使用 NSJSONSerialization

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8356842/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 15:43:40  来源:igfitidea点击:

How to use NSJSONSerialization

iosobjective-cjsonnsdictionary

提问by Logan Serman

I have a JSON string (from PHP's json_encode()that looks like this:

我有一个 JSON 字符串(来自 PHP json_encode(),看起来像这样:

[{"id": "1", "name":"Aaa"}, {"id": "2", "name":"Bbb"}]

I want to parse this into some sort of data structure for my iPhone app. I guess the best thing for me would be to have an array of dictionaries, so the 0th element in the array is a dictionary with keys "id" => "1"and "name" => "Aaa".

我想将其解析为我的 iPhone 应用程序的某种数据结构。我想对我来说最好的事情是拥有一个字典数组,所以数组中的第 0 个元素是一个带有键"id" => "1""name" => "Aaa".

I do not understand how the NSJSONSerializationstores the data though. Here is my code so far:

我不明白如何NSJSONSerialization存储数据。到目前为止,这是我的代码:

NSError *e = nil;
NSDictionary *JSON = [NSJSONSerialization 
    JSONObjectWithData: data 
    options: NSJSONReadingMutableContainers 
    error: &e];

This is just something I saw as an example on another website. I have been trying to get a read on the JSONobject by printing out the number of elements and things like that, but I am always getting EXC_BAD_ACCESS.

这只是我在另一个网站上看到的一个例子。我一直试图JSON通过打印出元素的数量和类似的东西来读取对象,但我总是得到EXC_BAD_ACCESS.

How do I use NSJSONSerializationto parse the JSON above, and turn it into the data structure I mentioned?

NSJSONSerialization上面的JSON如何解析,变成我说的数据结构?

回答by rckoenes

Your root json object is not a dictionary but an array:

您的根 json 对象不是字典而是数组:

[{"id": "1", "name":"Aaa"}, {"id": "2", "name":"Bbb"}]

This might give you a clear picture of how to handle it:

这可能会让您清楚地了解如何处理它:

NSError *e = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];

if (!jsonArray) {
  NSLog(@"Error parsing JSON: %@", e);
} else {
   for(NSDictionary *item in jsonArray) {
      NSLog(@"Item: %@", item);
   }
}

回答by srik

This is my code for checking if the received json is an array or dictionary:

这是我用于检查接收到的 json 是数组还是字典的代码:

NSError *jsonError = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&jsonError];

if ([jsonObject isKindOfClass:[NSArray class]]) {
    NSLog(@"its an array!");
    NSArray *jsonArray = (NSArray *)jsonObject;
    NSLog(@"jsonArray - %@",jsonArray);
}
else {
    NSLog(@"its probably a dictionary");
    NSDictionary *jsonDictionary = (NSDictionary *)jsonObject;
    NSLog(@"jsonDictionary - %@",jsonDictionary);
}

I have tried this for options:kNilOptions and NSJSONReadingMutableContainers and works correctly for both.

我已经为 options:kNilOptions 和 NSJSONReadingMutableContainers 尝试过这个,并且两者都可以正常工作。

Obviously, the actual code cannot be this way where I create the NSArray or NSDictionary pointer within the if-else block.

显然,实际代码不能像我在 if-else 块中创建 NSArray 或 NSDictionary 指针那样。

回答by Ole Begemann

It works for me. Your dataobject is probably niland, as rckoenes noted, the root object should be a (mutable) array. See this code:

这个对我有用。您的data对象可能是nil,正如 rckoenes 所指出的,根对象应该是一个(可变)数组。看到这个代码:

NSString *jsonString = @"[{\"id\": \"1\", \"name\":\"Aaa\"}, {\"id\": \"2\", \"name\":\"Bbb\"}]";
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *e = nil;
NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&e];
NSLog(@"%@", json);

(I had to escape the quotes in the JSON string with backslashes.)

(我必须用反斜杠转义 JSON 字符串中的引号。)

回答by zaph

Your code seems fine except the result is an NSArray, not an NSDictionary, here is an example:

您的代码看起来不错,除了结果是 an NSArray,而不是 an NSDictionary,这是一个示例:

The first two lines just creates a data object with the JSON, the same as you would get reading it from the net.

前两行只是用 JSON 创建了一个数据对象,就像你从网络上读取它一样。

NSString *jsonString = @"[{\"id\": \"1\", \"name\":\"Aaa\"}, {\"id\": \"2\", \"name\":\"Bbb\"}]";
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

NSError *e;
NSMutableArray *jsonList = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&e];
NSLog(@"jsonList: %@", jsonList);

NSLog contents (a list of dictionaries):

NSLog 内容(字典列表):

jsonList: (
           {
               id = 1;
               name = Aaa;
           },
           {
               id = 2;
               name = Bbb;
           }
           )

回答by kamalesh kumar yadav

[{"id": "1", "name":"Aaa"}, {"id": "2", "name":"Bbb"}]

In above JSON data, you are showing that we have an array contaning the number of dictionaries.

在上面的 JSON 数据中,您表明我们有一个包含字典数量的数组。

You need to use this code for parsing it:

您需要使用此代码来解析它:

NSError *e = nil;
NSArray *JSONarray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];
        for(int i=0;i<[JSONarray count];i++)
        {
            NSLog(@"%@",[[JSONarray objectAtIndex:i]objectForKey:@"id"]);
             NSLog(@"%@",[[JSONarray objectAtIndex:i]objectForKey:@"name"]);
        }

For swift 3/3+

快速 3/3+

   //Pass The response data & get the Array
    let jsonData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [AnyObject]
    print(jsonData)
    // considering we are going to get array of dictionary from url

    for  item  in jsonData {
        let dictInfo = item as! [String:AnyObject]
        print(dictInfo["id"])
        print(dictInfo["name"])
    }

回答by mahesh chowdary

The following code fetches a JSON object from a webserver, and parses it to an NSDictionary. I have used the openweathermap API that returns a simple JSON response for this example. For keeping it simple, this code uses synchronous requests.

以下代码从网络服务器获取 JSON 对象,并将其解析为 NSDictionary。我使用了 openweathermap API,它为这个例子返回一个简单的 JSON 响应。为简单起见,此代码使用同步请求。

   NSString *urlString   = @"http://api.openweathermap.org/data/2.5/weather?q=London,uk"; // The Openweathermap JSON responder
   NSURL *url            = [[NSURL alloc]initWithString:urlString];
   NSURLRequest *request = [NSURLRequest requestWithURL:url];
   NSURLResponse *response;
   NSData *GETReply      = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
   NSDictionary *res     = [NSJSONSerialization JSONObjectWithData:GETReply options:NSJSONReadingMutableLeaves|| NSJSONReadingMutableContainers error:nil];
   Nslog(@"%@",res);

回答by Olie

@rckoenes already showed you how to correctly get your data from the JSON string.

@rckoenes 已经向您展示了如何从 JSON 字符串中正确获取数据。

To the question you asked: EXC_BAD_ACCESSalmost always comes when you try to access an object after it has been [auto-]released. This is not specific to JSON [de-]serialization but, rather, just has to do with you getting an object and then accessing it after it's been released. The fact that it came via JSON doesn't matter.

对于您提出的问题:EXC_BAD_ACCESS几乎总是在您尝试访问已被[自动]释放的对象时出现。这并非特定于 JSON [反] 序列化,而是与您获取一个对象然后在它被释放后访问它有关。它来自 JSON 的事实并不重要。

There are many-many pages describing how to debug this -- you want to Google (or SO) obj-c zombie objectsand, in particular, NSZombieEnabled, which will prove invaluable to you in helping determine the source of your zombie objects. ("Zombie" is what it's called when you release an object but keep a pointer to it and try to reference it later.)

有很多页面描述了如何调试这个——你想要谷歌(或 SO)obj-c zombie objects,特别是NSZombieEnabled,这将证明对你帮助确定僵尸对象的来源非常宝贵。(当你释放一个对象但保留一个指向它的指针并稍后尝试引用它时,它被称为“僵尸”。)

回答by Zorayr

Swift 2.0 on Xcode 7 (Beta) with do/try/catch block:

带有 do/try/catch 块的 Xcode 7(Beta)上的 Swift 2.0:

// MARK: NSURLConnectionDataDelegate

func connectionDidFinishLoading(connection:NSURLConnection) {
  do {
    if let response:NSDictionary = try NSJSONSerialization.JSONObjectWithData(receivedData, options:NSJSONReadingOptions.MutableContainers) as? Dictionary<String, AnyObject> {
      print(response)
    } else {
      print("Failed...")
    }
  } catch let serializationError as NSError {
    print(serializationError)
  }
}

回答by Dinesh

NOTE: For Swift 3. Your JSON String is returning Array instead of Dictionary. Please try out the following:

注意:对于 Swift 3。您的 JSON 字符串返回 Array 而不是 Dictionary。请尝试以下操作:

        //Your JSON String to be parsed
        let jsonString = "[{\"id\": \"1\", \"name\":\"Aaa\"}, {\"id\": \"2\", \"name\":\"Bbb\"}]";

        //Converting Json String to NSData
        let data = jsonString.data(using: .utf8)

        do {

            //Parsing data & get the Array
            let jsonData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [AnyObject]

            //Print the whole array object
            print(jsonData)

            //Get the first object of the Array
            let firstPerson = jsonData[0] as! [String:Any]

            //Looping the (key,value) of first object
            for (key, value) in firstPerson {
                //Print the (key,value)
                print("\(key) - \(value) ")
            }

        } catch let error as NSError {
            //Print the error
            print(error)
        }

回答by user1462586

bad example, should be something like this {"id":1, "name":"something as name"}

不好的例子,应该是这样的 {"id":1, "name":"something as name"}

number and string are mixed.

数字和字符串混合。