将NSObject转换为NSDictionary [英] Converting NSObject to NSDictionary

查看:599
本文介绍了将NSObject转换为NSDictionary的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好我是一类NSObject类:

Hello I a class of type NSObject:

ProductDetails *details = [[ProductDetails alloc] init];
details.name = @"Soap1";
details.color = @"Red";
details.quantity = 4;

我想将details对象传递给字典。

I want to pass the "details" object to a dictionary.

我做了,

NSDictionary *dict = [NSDictionary dictionaryWithObject:details forKey:@"details"];

我将此dict传递给另一个执行JSONSerialization检查的方法:

I am passing this dict to another method which performs a check on JSONSerialization:

if(![NSJSONSerialization isValidJSONObject:dict])

我在这张支票上遇到了崩溃。我在这做错了吗?我知道我得到的细节是一个JSON对象,我将它分配给我的ProductDetails类中的属性。

And I am getting a crash on this check. Am I doing anything wrong here? I know that the details I am getting is a JSON object and I am assigning it to the properties in my ProductDetails class.

请帮助我。我是Objective-C的菜鸟。

Please help me. I am a noob in Objective-C.

我现在尝试过:

NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:(NSData*)details options:kNilOptions error:&error];

我需要的是将细节转换为NSData的简单方法。

All I need here is an easy way to convert details to NSData.

我注意到我的对象里面有一个数组可能就是为什么我尝试的所有方法都抛出异常。然而,由于这个问题变得越来越大,我已经开始了另一个问题线程,我已经显示了我在对象内部获得的数据 - https://stackoverflow.com/questions/19081104/convert-nsobject-to-nsdictionary

I noticed that I have an array inside my object may be thats why all the ways I tried is throwing an exception. However since this question is becoming to big, I have started an another question thread for it where I have displayed the data I am getting inside the object - https://stackoverflow.com/questions/19081104/convert-nsobject-to-nsdictionary

推荐答案

NSDictionary *details = {@"name":product.name,@"color":product.color,@"quantity":@(product.quantity)};

NSError *error; 
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:details 
                                                   options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                     error:&error];

if (! jsonData) {
    NSLog(@"Got an error: %@", error);
} else {
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

第二部分来源:从iOS中的NSDictionary生成JSON字符串

这篇关于将NSObject转换为NSDictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆