iOS JSON在实际设备上遇到麻烦

时间:2013-08-16 22:36:27

标签: javascript ios objective-c json coffeescript

出于某种原因,这适用于运行iOS 6+的模拟器,但不适用于运行iOS 5+的实际iPad。当我在iPad上运行我的应用程序时,它会给我这个错误(和其他人)。

Error parsing JSON: Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Badly formed object around character 316.) UserInfo=0x650260 {NSDebugDescription=Badly formed object around character 316.}

JSON used is this (which is passed from Javascript): {"functionname":"setItem","args":{"key":"http://localhost:3000/assets/tasks/task.js","value":"function Task(){this.steps=new Array,this.completed=!1,this.loaded=!1,this.stepCount=-1,this.points=0,this.newpoints=0,this.prevpoints=0,this.circleGesture=!1,this.customGesture=!1,this.subtaskCounter=0,this.className=/"/"}(goes on for a while since it is a js script)"}}

将iOS中的json字符串转换为json的代码

if ([[urlStr lowercaseString] hasPrefix:protocolPrefix])
{
    //strip protocol from the URL. We will get input to call a native method
    urlStr = [urlStr substringFromIndex:protocolPrefix.length];

    //Decode the url string
    urlStr = [urlStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSError *jsonError;

    //parse JSON input in the URL
    NSDictionary *callInfo = [NSJSONSerialization
                              JSONObjectWithData:[urlStr dataUsingEncoding:NSUTF8StringEncoding]
                              options:0
                              error:&jsonError];

    //check if there was error in parsing JSON input
    if (jsonError != nil)
    {
        NSLog(@"Error parsing JSON: %@",[jsonError debugDescription]);
        NSLog(@"%@", urlStr);
        return NO;
    } 

    ....
}

的CoffeeScript

callNativeFunction: (func, args, callback)->
  if global_phone_os == 'ios'
    url = "js2native://"
    callInfo = {}
    callInfo.functionname = func
    if args?
      callInfo.args = args
    if callback?
      cid = Math.random().toString(36).substr(2,10)
      @callback[cid] = callback
      callInfo.callback_id = cid
    url += JSON.stringify callInfo
    @openCustomURLinIFrame url

如何让这个在模拟器和实际设备上运行?

更新

到目前为止,我认为我修复了它。如果我这样做,这将被标记为答案。我必须在coffeescript中执行以下操作:

url += encodeURIComponent JSON.stringify callInfo

这有所不同。

感谢。

2 个答案:

答案 0 :(得分:0)

在我看来,您正在尝试解析url字符串而不是解析URL内容。你确定它在模拟器中有效吗?

您的密码:

//parse JSON input in the URL
NSDictionary *callInfo = [NSJSONSerialization
                          JSONObjectWithData:[urlStr dataUsingEncoding:NSUTF8StringEncoding]
                          options:0
                          error:&jsonError];

我认为应该是:

//parse JSON input in the URL
NSDictionary *callInfo = [NSJSONSerialization
                          JSONObjectWithData:[NSData dataWithContentsOfURL:
                urlStr],
                          options:0
                          error:&jsonError];

答案 1 :(得分:0)

这确实解决了这个问题。

url += encodeURIComponent JSON.stringify callInfo