11.9~11.10系列化反系列化Json

来源:互联网 发布:锡林浩特发改委大数据 编辑:程序博客网 时间:2024/05/07 23:31

11.9. Serializing Arrays and Dictionaries into JSON

序列化:dictionary or  array ——> Json string

对象仅支持NSString, NSNumber, NSArray, NSDictionary,nil


-(void)testJSONSerialization

{

    NSDictionary *dictionary =

    @{

      @"First Name" :@"Anthony",

      @"Last Name" :@"Robbins",

      @"Age" : @51,

      @"children" :@[

              @"Anthony's Son 1",

              @"Anthony's Daughter 1",

              @"Anthony's Son 2",

              @"Anthony's Son 3",

              @"Anthony's Daughter 2"

              ],

      };

    NSError *error = nil;

    NSData *jsonData = [NSJSONSerialization

                       dataWithJSONObject:dictionary

                        options:NSJSONWritingPrettyPrinted

                       error:&error];

    if ([jsonData length] > 0 && error == nil){

        NSLog(@"Successfully serialized the dictionary into data.");

        NSString *jsonString =

        [[NSStringalloc]initWithData:jsonData

                             encoding:NSUTF8StringEncoding];

        NSLog(@"JSON String = %@", jsonString);

    }

    else if ([jsonData length] == 0 && error == nil){

        NSLog(@"No data was returned after serialization.");

    }

    else if (error != nil){

        NSLog(@"An error happened = %@", error);

    }

}


打印:

2014-06-26 15:18:27.607 cookbook7[742:907] Successfully serialized the dictionary into data.

2014-06-26 15:18:27.611 cookbook7[742:907] JSON String = {

  "Last Name" : "Robbins",

  "First Name" : "Anthony",

  "children" : [

    "Anthony's Son 1",

    "Anthony's Daughter 1",

    "Anthony's Son 2",

    "Anthony's Son 3",

    "Anthony's Daughter 2"

  ],

  "Age" : 51

}


11.10. Deserializing JSON into Arrays and Dictionaries

反序列化:Json string ——>dictionary or  array

-(void)testJSONSerialization

{

    NSDictionary *dictionary =

    @{

      @"First Name" :@"Anthony",

      @"Last Name" :@"Robbins",

      @"Age" : @51,

      @"children" :@[

              @"Anthony's Son 1",

              @"Anthony's Daughter 1",

              @"Anthony's Son 2",

              @"Anthony's Son 3",

              @"Anthony's Daughter 2"

              ],

      };

    NSError *error = nil;

    NSData *jsonData = [NSJSONSerialization

                       dataWithJSONObject:dictionary

                        options:NSJSONWritingPrettyPrinted

                       error:&error];

    if ([jsonData length] > 0 && error == nil){

        NSLog(@"Successfully serialized the dictionary into data.");

        NSString *jsonString =

        [[NSStringalloc]initWithData:jsonData

                             encoding:NSUTF8StringEncoding];

        NSLog(@"JSON String = %@", jsonString);

        [selftestDeserialization:jsonString];//把系列化后的jsonstring反系列化

    }

    else if ([jsonData length] == 0 && error == nil){

        NSLog(@"No data was returned after serialization.");

    }

    else if (error != nil){

        NSLog(@"An error happened = %@", error);

    }

}


-(void)testDeserialization:(NSString*)jsonStr

{

    NSData* jsonData = [jsonStrdataUsingEncoding:NSUTF8StringEncoding];

    NSError *error = nil;

    id jsonObject = [NSJSONSerialization

                    JSONObjectWithData:jsonData

                     options:NSJSONReadingAllowFragments

                    error:&error];

    if (jsonObject != nil && error == nil){

        NSLog(@"Successfully deserialized...");

        if ([jsonObject isKindOfClass:[NSDictionaryclass]]){

            NSDictionary *deserializedDictionary = jsonObject;

            NSLog(@"Deserialized JSON Dictionary = %@",

                  deserializedDictionary);

        }elseif ([jsonObjectisKindOfClass:[NSArrayclass]]){

            NSArray *deserializedArray = (NSArray *)jsonObject;

            NSLog(@"Deserialized JSON Array = %@", deserializedArray);

        }

        else {

            /* Some other object was returned. We don't know how to

             deal with this situation as the deserializer only

             returns dictionaries or arrays */

            NSLog(@"not NSDictionary not NSArray jsonObject=%@",jsonObject);

        }

    }elseif (error !=nil){

        NSLog(@"An error happened while deserializing the JSON data.");

    }

}


打印:

2014-06-26 15:26:10.788 cookbook7[758:907] Successfully serialized the dictionary into data.

2014-06-26 15:26:10.792 cookbook7[758:907] JSON String = {

  "Last Name" : "Robbins",

  "First Name" : "Anthony",

  "children" : [

    "Anthony's Son 1",

    "Anthony's Daughter 1",

    "Anthony's Son 2",

    "Anthony's Son 3",

    "Anthony's Daughter 2"

  ],

  "Age" : 51

}

2014-06-26 15:26:10.795 cookbook7[758:907] Successfully deserialized...

2014-06-26 15:26:10.797 cookbook7[758:907] Deserialized JSON Dictionary = {

    Age = 51;

    "First Name" = Anthony;

    "Last Name" = Robbins;

    children =     (

        "Anthony's Son 1",

        "Anthony's Daughter 1",

        "Anthony's Son 2",

        "Anthony's Son 3",

        "Anthony's Daughter 2"

    );

}


JSONObjectWithData:options:error:参数

NSJSONReadingMutableContainers:是否返回Mutable实例,加则返回NSMutableArray NSMutableDictionary;不加,则返回NSArray NSDictionary


NSJSONReadingMutableLeaves:叶节点是否封装成NSMutableString.

NSJSONReadingAllowFragments:允许反系列化json数据,即使顶层对象不是NSArray NSDictionary


看看例子:


    [selftestDeserialization:@"123"];

    [selftestDeserialization:@"\"abcd\""];

    [selftestDeserialization:@"abcdefg"];

打印:

2014-06-26 15:54:00.304 cookbook7[907:907] Successfully deserialized...

2014-06-26 15:54:00.308 cookbook7[907:907] not NSDictionary not NSArray jsonObject=123

2014-06-26 15:54:00.310 cookbook7[907:907] Successfully deserialized...

2014-06-26 15:54:00.312 cookbook7[907:907] not NSDictionary not NSArray jsonObject=abcd

2014-06-26 15:54:00.318 cookbook7[907:907] An error happened while deserializing the JSON data.error=Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Invalid value around character 0.) UserInfo=0x1cd81340 {NSDebugDescription=Invalid value around character 0.}


0 0