在目标C中生成js对象文字

时间:2013-09-10 20:31:17

标签: javascript objective-c json literals object-literal

我正在尝试从目标C生成一些javascript。我有一个简单的objective-c对象:只有NSString s,NSArray s,NSDictionary s和{{1 s - 我想将它作为对象文字插入到javascript中。最好的方法是什么?

到目前为止,我已设法序列化对象并获取JSON字符串,但JSON并不完全等同于javascript对象文字。我可以将其作为NSNumber调用插入,但这似乎效率低下:

JSON.parse('%@')

1 个答案:

答案 0 :(得分:0)

这是完整的代码:

//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字符!