将 iOS 目标 c 对象转换为 JSON 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10548429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 18:19:57  来源:igfitidea点击:

Convert an iOS objective c object to a JSON string

iosjsonserializationnsarray

提问by Sankar

I have an objective C class like,

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

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

I have an NSMutableArray of instances of this message class. I want serialize all the instances in the NSMutableArray into a JSON file, using the new JSONSerialization APIs in iOS 5 SDK. How can I do this ?

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

Is creating a NSDictionary of each key, by iterating through each instance of the elements in the NSArray ? Can someone help with code of how to solve this ? I am not able to get good results in Google, as "JSON" skews the results to server-side calls and transfer of data instead of serialization. Thanks a lot.

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

EDIT:

编辑:

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

回答by Damo

EDIT: I have made a dummy app that should be a good example for you.

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

I create a Message class from your code snippet;

我从你的代码片段创建了一个 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];
}

Then I set up an NSArray of two messages in the AppDelegate. The trick is that not only does the top level object (notifications in your case) need to be serializable but so do all the elements that notifications contains: Thats why I created the dictionarymethod in the Message class.

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

//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

The output when I run the application is thus:

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

2012-05-11 11:58:36.018 stack[3146:f803] JSON Output: [ { "msg" : "c", "from" : "a", "date" : "b" }, { "msg" : "f", "from" : "d", "date" : "e" } ]

2012 年 5 月 11 日 11:58:36.018 堆栈 [3146:f803] JSON 输出:[{“msg”:“c”,“来自”:“a”,“日期”:“b”},{“msg” :“f”,“来自”:“d”,“日期”:“e”}]

ORIGINAL ANSWER:

原始答案:

Is thisthe documentation you are looking for?

这个你正在寻找的文件?

回答by X Sham

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, shortand float. It can also cater nested-complex JSON. It handles error checking for you.

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

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

回答by Brad Parks

Note: This will only work with serializable objects. This answer was provided above in an edit to the question itself, but I always look for answers in the "answers" section myself ;-)

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

- (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;
}

回答by Burrows Wang

Here is a library i used in my projects BWJSONMatcher, which can help you easily match your json string up with your data model with no more than one line of code.

这是我在我的项目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];
...