How to parse JSON in iOS App

前端 未结 6 1979
栀梦
栀梦 2020-11-29 09:55

Im getting a response from twitter in the form of a string,

What I need is to send the parts where is a comment to an array,

here an example of the string

6条回答
  •  执笔经年
    2020-11-29 10:19

    I haven't done JSON parsing myself in an iOS App, but you should be able to use a library like the json-framework. This library will allow you to easily parse JSON and generate json from dictionaries / arrays (that's really all JSON is composed of).

    SBJson docs:

    JSON is mapped to Objective-C types in the following way:

    • null -> NSNull
    • string -> NSString
    • array -> NSMutableArray
    • object -> NSMutableDictionary
    • true -> NSNumber's -numberWithBool:YES
    • false -> NSNumber's -numberWithBool:NO
    • integer up to 19 digits -> NSNumber's -numberWithLongLong:
    • all other numbers -> NSDecimalNumber

    Since Objective-C doesn't have a dedicated class for boolean values, these turns into NSNumber instances. However, since these are initialised with the -initWithBool: method they round-trip back to JSON properly. In other words, they won't silently suddenly become 0 or 1; they'll be represented as 'true' and 'false' again.

    As an optimisation integers up to 19 digits in length (the max length for signed long long integers) turn into NSNumber instances, while complex ones turn into NSDecimalNumber instances. We can thus avoid any loss of precision as JSON allows ridiculously large numbers.

    @page objc2json Objective-C to JSON

    Objective-C types are mapped to JSON types in the following way:

    • NSNull -> null
    • NSString -> string
    • NSArray -> array
    • NSDictionary -> object
    • NSNumber's -initWithBool:YES -> true
    • NSNumber's -initWithBool:NO -> false
    • NSNumber -> number

    @note In JSON the keys of an object must be strings. NSDictionary keys need not be, but attempting to convert an NSDictionary with non-string keys into JSON will throw an exception.

    NSNumber instances created with the -numberWithBool: method are converted into the JSON boolean "true" and "false" values, and vice versa. Any other NSNumber instances are converted to a JSON number the way you would expect.

    Tutorials

    Are there any tutorials? Yes! These are all tutorials provided by third-party people:

    JSON Framework for iPhone - a Flickr tutorial in three parts by John Muchow. JSON Over HTTP On The iPhone - by Dan Grigsby. AS3 to Cocoa touch: JSON by Andy Jacobs.

    There are other libraries you can check out as well like TouchJSON, JSONKit, Yet Another JSON Library

提交回复
热议问题