Serialize and Deserialize Objective-C objects into JSON

后端 未结 7 1770
花落未央
花落未央 2020-11-30 01:05

I need to serialize and deserialize objective-c objects into JSON to store in CouchDB. Do people have any example code for best practice for a general solution? I looked a

7条回答
  •  迷失自我
    2020-11-30 01:55

    You can easily add JSON capability to NSObject class with the help of NSDictionary,NSArray and NSJSONSerialization

    Serialization:

    Just see the example it will be very easy to understand.

    Adding JSON Capability to NSObject Class:-

    @interface JsonClassEmp : NSObject
    
    @property(strong,nonatomic)NSString *EmpName,*EmpCode;
    
    -(NSDictionary*)GetJsonDict;
    
    @end
    
    @implementation JsonClassEmp
    
    @synthesize EmpName,EmpCode;
    
    //Add all the properties of the class in it.
    -(NSDictionary*)GetJsonDict
    {
        return [NSDictionary dictionaryWithObjectsAndKeys:EmpName,@"EmpName",EmpCode,@"EmpCode", nil];
    }
    
    @end
    

    JSON String Generator:-

    In iOS 5, Apple introduced NSJSONSerialization, for parsing JSON strings so by using that we will generate JSON string.

    -(NSString*)GetJSON:(id)object
    {
        NSError *writeError = nil;
    
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object options:NSJSONWritingPrettyPrinted error:&writeError];
    
        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
        return jsonString;
    }
    

    Moving towards Apple’s implementation is always safer to use since you have the guarantee that it will be maintained and kept up to date.

    Way to use:-

    - (void)viewDidLoad
    {
        [super viewDidLoad];
    
        JsonClassEmp *emp1=[[JsonClassEmp alloc]init];
    
        [emp1 setEmpName:@"Name1"];
    
        [emp1 setEmpCode:@"1"];
    
        JsonClassEmp *emp2=[[JsonClassEmp alloc]init];
    
        [emp2 setEmpName:@"Name2"];
    
        [emp2 setEmpCode:@"2"];
    
        //Add the NSDictionaries of the instances in NSArray
        NSArray *arrEmps_Json=@[emp1.GetJsonDict,emp2.GetJsonDict];
    
        NSLog(@"JSON Output: %@", [self GetJSON:arrEmps_Json]);
    
    }
    

    Reference

    Deserialization:

    It's usual way of getting the deserialized data into NSDictionary or NSArray then assign it to class properties.

    I am sure using the methods and ideas used above you can serialize & deserialize complex json easily.

提交回复
热议问题