我正在尝试从 Objective C 生成一些 javascript。我有一个简单的 Objective-C 对象:只有 NSString
、NSArray
、NSDictionary
s 和 NSNumber
s - 我想将其作为对象文字插入到 javascript 中。最好的方法是什么?
到目前为止,我已经成功序列化该对象并获取 JSON 字符串,但 JSON 并不完全等同于 javascript 对象文字。我可以将其作为 JSON.parse('%@')
调用插入,但这似乎效率低下:
(controller.createWindow).apply((controller), JSON.parse('[\"LoggedIn\",3,1,[0,0,480,320],false,false]'))
最佳答案
完整代码如下:
//turn an NSObject into an NSString
+ (NSString *)jsonDumps:(id)obj {
NSError *error;
NSData *utf8stringified = [NSJSONSerialization dataWithJSONObject:obj options:0 error:&error];
if (utf8stringified == nil) {
[NSException raise:@"Failed to jsonify arguments" format:@"Failed to jsonify arguments %@: %@",
obj, error];
}
NSString *stringified = [[[NSString alloc] initWithData:utf8stringified encoding:NSUTF8StringEncoding]
autorelease];
return stringified;
}
//turn a JSON string into a JS literal
+(NSString *)jsonToJSLit:(NSString *)jsonString {
NSMutableString *s = [NSMutableString stringWithString:jsonString];
[s replaceOccurrencesOfString:@"\u2028" withString:@"\\u2028" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];
[s replaceOccurrencesOfString:@"\u2029" withString:@"\\u2029" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];
return [NSString stringWithString:s];
}
//turn an object into a JS string literal
+(NSString *)objToJSLiteral:(id)obj {
return [self jsonToJSLit:[self jsonDumps:obj]];
}
我认为 JSON 和 JS 文字之间有更多区别,但显然只是这两个 unicode 字符!
关于javascript - 在 Objective C 中生成 js 对象文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18728228/