javascript - 在 Objective C 中生成 js 对象文字

标签 javascript objective-c json literals object-literal

我正在尝试从 Objective C 生成一些 javascript。我有一个简单的 Objective-C 对象:只有 NSStringNSArrayNSDictionarys 和 NSNumbers - 我想将其作为对象文字插入到 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/

相关文章:

javascript - 访问对象内的对象属性

javascript - Password_hash() 提交前需要预哈希吗?

ios - subview 约束打破父 View 约束

javascript - JSON 响应不是来自 php 的对象

javascript - Android浏览器快速连续两次乱码事件

ios - 调用 instantiateViewControllerWithIdentifier 始终返回全屏大小

ios - Objective-C 相当于 Haskell 的 intersperse 函数?或在另一个对象上加入对象?

javascript - 使用json数据在angularjs中绘制折线图

json - 使用 jq 从 json 中提取数据时将数组值写入同一行

javascript - 函数需要改进,应该返回一个 _ 和一个数字(不管有多长)