NSJSONSerialization from NSString

后端 未结 4 626
眼角桃花
眼角桃花 2020-12-03 00:41

Is it possible if I have a NSString and I want to use NSJSONSerialization? How do I do this?

相关标签:
4条回答
  • 2020-12-03 01:10

    I wrote a blog post that demonstrates how to wrap the native iOS JSON class in a general protocol together with an implementation that use the native iOS JSON class.

    This approach makes it a lot easier to use the native functionality and reduces the amount of code you have to write. Furthermore, it makes it a lot easier to switch out the native implementation with, say, JSONKit, if the native one would prove to be insufficient.

    http://danielsaidi.com/blog/2012/07/04/json-in-ios

    The blog post contains all the code you need. Just copy / paste :)

    Hope it helps!

    0 讨论(0)
  • 2020-12-03 01:18

    You can convert your string to NSData by saying:

    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    

    You can then use it with NSJSONSerialization. Note however that NSJSONSerialization is iOS5 only, so you might be better off using a library like TouchJSON or JSONKit, both of which let you work directly with strings anyway, saving you the step of converting to NSData.

    0 讨论(0)
  • 2020-12-03 01:27

    First you will need to convert your NSString to NSData by doing the following

    NSData *data = [stringData dataUsingEncoding:NSUTF8StringEncoding];
    

    then simply use the JSONObjectWithData method to convert it to JSON

    id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    
    0 讨论(0)
  • 2020-12-03 01:27

    You need to convert your NSString to NSData, at that point you can use the +[NSJSONSerialization JSONObjectWithData:options:error:] method.

    NSString * jsonString = YOUR_STRING;
    NSData * data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError * error = nil;
    id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
    if (!json) {
        // handle error
    }
    
    0 讨论(0)
提交回复
热议问题