- JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy to read and write with a completely language-independent text format, and is easy for machine parsing and generation
- There are two kinds of structures for JSON files:
1 object: A collection of name/value pairs, starting with "{", Ending with "}", separated by ":" In the middle of the name and value
2 array: An ordered list of values, starting with "[", Ending with "]", data in the middle, data separated by ","
(Data type in JSON: string, numeric bool, object, array)
For example:
{"reason":"Success","result":[ { "MovieID":"215977", "Moviename":"Lone shadow of the Forest", "Pic_url":"http://v.juhe.cn/movie/picurl?2583247" }, { "MovieID":"215874", "Moviename":"Where to come from, where to go", "Pic_url":"http://v.juhe.cn/movie/picurl?2583542" }, { "MovieID":"215823", "Moviename":"one day.", "Pic_url":"http://v.juhe.cn/movie/picurl?2583092" }],"Error_code": 0 }
Perform JSON parsing steps
- Get the JSON file path
- Convert to NSData type
- Parsing JSON data
The code is as follows:
- (void) Jsonparser {//step1: File path NSString*jsonpath = [[NSBundleMainbundle] pathforresource:@"Movielist"oftype:@"TXT"];//STEP2: Convert to NSData typeNSData *jsondata = [NSData Datawithcontentsoffile:jsonpath];//STEP3. Parsing JSON data Nserror*error;///second parameter: //nsjsonreadingmutablecontainers = (1UL << 0), parsing is done to return a variable array or dictionary type. //nsjsonreadingmutableleaves = (1UL << 1), parsing completed returns a type of nsmutablestring, which is less useful in iOS7 and above. //nsjsonreadingallowfragments = (1UL << 2) allows the outermost layer of the JSON string to be neither an array nor a dictionary, but must be a valid JSON fragment, such as a JSON string that can be a string. nsdictionary*resultdic = [nsjsonserialization jsonobjectwithdata:jsondata options:nsjsonreadingallowfragments Error:&error] ;if(Resultdic) {//Determine if parsing is getting normal data //Determines whether the current object supports JSON format if([Nsjsonserialization Isvalidjsonobject:resultdic]) {//Convert dictionary to JSON stringNSData *strdata = [nsjsonserialization datawithjsonobject:resultdic options:nsjsonwritingprettyprinted error:& ERROR];//Determine if the strdata has a value if(strdata) {//Convert data to a string NSString*STR = [[NSStringAlloc] Initwithdata:strdata encoding:nsutf8stringencoding];NSLog(@"%@", str); } } }}
JSON parsing of iOS data parsing