且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

json_encode等同于objective-c

更新时间:2023-02-12 19:15:36

你可以看看

  +(NSData *)dataWithJSONObject:(id)obj选项:(NSJSONWritingOptions)选择错误:(NSError **)错误

你从苹果基金会课程的某些对象中获取JSON数据。如果你需要一个字符串,你可以使用:

   - (id)initWithData:(NSData *)数据编码:(NSStringEncoding)编码NSString的

。可能导致以下情况:

  NSString * string = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:YOUR_OBJECT_HERE options:0 error:nil] encoding:NSUTF8StringEncoding] autorelease]; 


I need to write the equivalent to this php code

json_encode(utf8_encode())

in objective-c

I've implemented the equivalent to utf8_encode with

[NSString stringWithCString:[testString cStringUsingEncoding:NSUTF8StringEncoding] encoding:NSASCIIStringEncoding]

So now, I need to implement the equivalent to json_encode php function.

input : "http://www.mydomain.com/s?c=Théâtre,Cinéma"

expected output :  "http://www.mydomain.com/s?c=Th\u00c3\u00a9\u00c3\u00a2tre,Cin\u00c3\u00a9ma"

Does anyone have an efficient way to do that?

You could have a look at

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

You get back JSON data from some object of Apples Foundation classes. If you need a string, you could use:

- (id)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding

of NSString. Might result in something like:

NSString *string = [[[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:YOUR_OBJECT_HERE options:0 error:nil] encoding:NSUTF8StringEncoding] autorelease];