Convert an iOS objective c object to a JSON string

后端 未结 4 1341
野趣味
野趣味 2020-11-29 05:34

I have an objective C class like,

@interface message : NSObject {
 NSString *from;
 NSString *date;
 NSString *msg;
}

I have an NSMutableAr

4条回答
  •  粉色の甜心
    2020-11-29 05:52

    Now you can solve this problem easily using JSONModel. JSONModel is a library that generically serialize/deserialize your object based on Class. You can even use non-nsobject based for property like int, short and float. It can also cater nested-complex JSON. It handles error checking for you.

    Deserialize example. in header file:

    #import "JSONModel.h"
    
    @interface Message : JSONModel 
    @property (nonatomic, strong) NSString* from;
    @property (nonatomic, strong) NSString* date;
    @property (nonatomic, strong) NSString* message;
    @end
    

    in implementation file:

    #import "JSONModelLib.h"
    #import "yourPersonClass.h"
    
    NSString *responseJSON = /*from somewhere*/;
    Message *message = [[Message alloc] initWithString:responseJSON error:&err];
    if (!err)
    {
       NSLog(@"%@  %@  %@", message.from, message.date, message.message):
    }
    

    Serialize Example. In implementation file:

    #import "JSONModelLib.h"
    #import "yourPersonClass.h"
    
    Message *message = [[Message alloc] init];
    message.from = @"JSON beast";
    message.date = @"2012";
    message.message = @"This is the best method available so far";
    
    NSLog(@"%@", [person toJSONString]);
    

提交回复
热议问题