【问题标题】:Convert an iOS objective c object to a JSON string将 iOS 目标 c 对象转换为 JSON 字符串
【发布时间】:2012-05-19 21:03:16
【问题描述】:

我有一个客观的 C 类,例如,

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

我有一个 NSMutableArray 这个消息类的实例。我想使用 iOS 5 SDK 中的新 JSONSerialization API 将 NSMutableArray 中的所有实例序列化为 JSON 文件。我该怎么做?

是否通过遍历 NSArray 中元素的每个实例来创建每个键的 NSDictionary ?有人可以提供如何解决这个问题的代码吗?我无法在 Google 中获得好的结果,因为“JSON”将结果偏向服务器端调用和数据传输而不是序列化。非常感谢。

编辑:

NSError *writeError = nil; 
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:notifications options:NSJSONWritingPrettyPrinted error:&writeError];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; 
NSLog(@"JSON Output: %@", jsonString);

【问题讨论】:

    标签: ios json serialization nsarray


    【解决方案1】:

    编辑:我制作了一个虚拟应用程序,对你来说应该是一个很好的例子。

    我从你的代码 sn-p 创建了一个 Message 类;

    //Message.h
    @interface Message : NSObject {
        NSString *from_;
        NSString *date_;
        NSString *msg_;
    }
    
    @property (nonatomic, retain) NSString *from;
    @property (nonatomic, retain) NSString *date;
    @property (nonatomic, retain) NSString *msg;
    
    -(NSDictionary *)dictionary;
    
    @end
    
    //Message.m
    #import "Message.h"
    
    @implementation Message
    
    @synthesize from = from_;
    @synthesize date = date_;
    @synthesize msg = mesg_;
    
    -(void) dealloc {
        self.from = nil;
        self.date = nil;
        self.msg = nil;
        [super dealloc];
    }
    
    -(NSDictionary *)dictionary {
        return [NSDictionary dictionaryWithObjectsAndKeys:self.from,@"from",self.date,    @"date",self.msg, @"msg", nil];
    }
    

    然后我在 AppDelegate 中设置了两个消息的 NSArray。诀窍是不仅顶级对象(在您的情况下为通知)需要可序列化,而且通知包含的所有元素也需要可序列化:这就是我在 Message 类中创建 dictionary 方法的原因。

    //AppDelegate.m
    ...
    Message* message1 = [[Message alloc] init];
    Message* message2 = [[Message alloc] init];
    
    message1.from = @"a";
    message1.date = @"b";
    message1.msg = @"c";
    
    message2.from = @"d";
    message2.date = @"e";
    message2.msg = @"f";
    
    NSArray* notifications = [NSArray arrayWithObjects:message1.dictionary, message2.dictionary, nil];
    [message1 release];
    [message2 release];
    
    
    NSError *writeError = nil; 
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:notifications options:NSJSONWritingPrettyPrinted error:&writeError];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; 
    NSLog(@"JSON Output: %@", jsonString);
    
    @end
    

    我运行应用程序时的输出是这样的:

    2012-05-11 11:58:36.018 堆栈[3146:f803] JSON 输出:[ { “味精”:“c”, “来自”:“一个”, “日期”:“b” }, { “味精”:“f”, “来自”:“d”, “日期”:“e” } ]

    原始答案:

    this 是您要查找的文档吗?

    【讨论】:

    • OP 首先需要将他的对象转换为字典,但这很简单(静态方法可以解决问题)
    • Damo:该页面没有说明如何将自定义类数组转换为 JSON。这就是我正在努力寻找的。​​span>
    • 如果你所有的类 ivars 都是 NSString 那么它应该可以神奇地工作....警告:我还没有尝试过。
    • @Damo 我收到一个运行时错误:由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:'-[message dictionaryRepresentation]:无法识别的选择器已发送到实例
    • @Damo NSError *writeError = nil; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:notifications options:NSJSONWritingPrettyPrinted error:&writeError]; NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; NSLog(@"JSON 输出:%@", jsonString);通知是消息对象的 NSMutableArray
    【解决方案2】:

    现在您可以使用JSONModel 轻松解决此问题。 JSONModel 是一个基于 Class 对对象进行一般序列化/反序列化的库。你甚至可以对int、short 和float 等属性使用非nsobject。它还可以满足嵌套复杂的 JSON。它会为您处理错误检查。

    反序列化示例。在头文件中:

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

    在实现文件中:

    #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):
    }
    

    序列化示例。在实现文件中:

    #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]);
    

    【讨论】:

    • 谢谢!这个图书馆太有用了。
    • 如果我们想使用 JSONModel 序列化消息数组怎么办?
    【解决方案3】:

    注意:这仅适用于可序列化的对象。这个答案是在上面对问题本身的编辑中提供的,但我自己总是在“答案”部分寻找答案;-)

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

    【讨论】:

    • 嗨。如何转换 NSObject 的数组。谢谢你:)
    • 嘿@kemdo - 不确定 - 我不再做 ios dev 了,所以不能说....祝你好运!
    【解决方案4】:

    这是我在我的项目中使用的一个库BWJSONMatcher,它可以帮助您轻松地将您的 json 字符串与您的数据模型匹配,只需一行代码。

    ...
    NSString *jsonString = @"{your-json-string}";
    YourValueObject *dataModel = [YourValueObject fromJSONString:jsonString];
    
    NSDictionary *jsonObject = @{your-json-object};
    YourValueObject *dataModel = [YourValueObject fromJSONObject:jsonObject];
    ...
    YourValueObject *dataModel = instance-of-your-value-object;
    NSString *jsonString = [dataModel toJSONString];
    NSDictionary *jsonObject = [dataModel toJSONObject];
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-26
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-28
      • 1970-01-01
      相关资源
      最近更新 更多