如何将一个NSDictionary转换为JSON对象?(复制)

时间:2022-12-25 13:45:23

This question already has an answer here:

这个问题已经有了答案:

I'm still learning JSON, and using SBJSON. How would I go about taking an NSDictionary and converting it into a JSON object similar to this:

我还在学习JSON,并使用SBJSON。我如何使用NSDictionary并将其转换为JSON对象,类似如下:

{"id":"123","list":"456","done":1,"done_date":1305016383}

3 个解决方案

#1


6  

Use the category that SBJSON adds to NSDictionary:

使用SBJSON添加到NSDictionary的类别:

NSString *jsonString = [dictionary JSONRepresentation];

Just name the keys and values appropriately in the dictionary and SBJSON will do the work for you

只需在字典中适当地命名键和值,SBJSON将为您完成这项工作

#2


3  

There is a JSON-API (since iOS5 and OS X 10.7) in the official iOS-SDK it's called:

在官方的iOS-SDK中有一个JSON-API(因为iOS5和OS X 10.7)叫做:

+ (NSData *)dataWithJSONObject:(id)obj
                       options:(NSJSONWritingOptions)opt
                         error:(NSError **)error

See Guillaume's post for more information how to use it: https://*.com/a/9020923/261588

更多信息请参见Guillaume的文章:https://*.com/a/9020923/261588

Works like a charm.

就像一个魅力。

#3


2  

For those that are using JSONKit instead of SBJSON:

对于使用JSONKit而不是SBJSON的用户:

JSONKit also provides a category for NSDictionary

JSONKit还为NSDictionary提供了一个类别

NSString *jsonString = [dictionary JSONStringWithOptions:JKSerializeOptionNone error:nil]

#1


6  

Use the category that SBJSON adds to NSDictionary:

使用SBJSON添加到NSDictionary的类别:

NSString *jsonString = [dictionary JSONRepresentation];

Just name the keys and values appropriately in the dictionary and SBJSON will do the work for you

只需在字典中适当地命名键和值,SBJSON将为您完成这项工作

#2


3  

There is a JSON-API (since iOS5 and OS X 10.7) in the official iOS-SDK it's called:

在官方的iOS-SDK中有一个JSON-API(因为iOS5和OS X 10.7)叫做:

+ (NSData *)dataWithJSONObject:(id)obj
                       options:(NSJSONWritingOptions)opt
                         error:(NSError **)error

See Guillaume's post for more information how to use it: https://*.com/a/9020923/261588

更多信息请参见Guillaume的文章:https://*.com/a/9020923/261588

Works like a charm.

就像一个魅力。

#3


2  

For those that are using JSONKit instead of SBJSON:

对于使用JSONKit而不是SBJSON的用户:

JSONKit also provides a category for NSDictionary

JSONKit还为NSDictionary提供了一个类别

NSString *jsonString = [dictionary JSONStringWithOptions:JKSerializeOptionNone error:nil]