ios JSON 文本未以数组或对象开头,并且没有设置允许片段的选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21452385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSON text did not start with array or object and option to allow fragments not set
提问by LvN
I'm sending this json response from server for a request to my IOS 7 app.
我正在从服务器发送这个 json 响应以请求我的 IOS 7 应用程序。
{
"root": {
"success": "1",
"message": "Successfully retrieved data.",
"data": {
"records": [
{
"receipt_key": "xxxxxxxx",
"receipt_id": "xxxxxxxx",
"store_name": "xxxxxx",
"amount": "xxxx",
"date_purchase": "xxxxxxxx",
"is_processed": "x",
"created_on": "xxxxxxxx",
"modified_on": "xxxxxxxx",
"modified_on_millis": "xxxxxxxx",
"user_folder": "xxxxxxxx",
"category_id": "xxxxxxxx",
"is_deleted": "x",
"currency_id": "xxxxxxxx"
}
]
}
}
}
I use the following code for parsing the above json to NSDictionary object.
我使用以下代码将上述 json 解析为 NSDictionary 对象。
NSMutableDictionary *json=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
But I'm getting this error on the above code.
但是我在上面的代码中遇到了这个错误。
Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn't be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x8a8a700 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
错误域=NSCocoaErrorDomain 代码=3840“无法完成操作。(Cocoa 错误 3840。)”(JSON 文本未以数组或对象开头,并且未设置允许片段的选项。) UserInfo=0x8a8a700 {NSDebugDescription=JSON 文本没有以数组或对象开头,并且没有设置允许片段的选项。}
回答by Dave Burke
I ran into the same error when consuming a feed from a php page. Just as you encountered, the resulting json string passed a visual inspection, but would fail to serialize. My suspicion was that there was a hidden character somewhere the feed, so I converted each character to its unicode decimal equivalent and examined the results:
从 php 页面使用提要时,我遇到了同样的错误。正如您遇到的那样,生成的 json 字符串通过了视觉检查,但无法序列化。我怀疑提要的某个地方有一个隐藏的字符,所以我将每个字符转换为它的 unicode 十进制等价物并检查结果:
NSString *feedStr = [[NSString alloc] initWithData:feedData encoding:NSUTF8StringEncoding];
for(int i=0; i<[feedStr length]; ++i)
{
unichar c = [feedStr characterAtIndex:i];
NSLog(@"decimal char %d", c);
}
I found that before the first character and after the last was the character #65279. After a quick google search I found What is this char? 65279, where this was identified as a byte order mark.
我发现在第一个字符之前和最后一个字符之后是#65279。快速谷歌搜索后,我发现这是什么字符?65279,这里被识别为字节顺序标记。
In my case, I was able to fix this at the source by opening and saving all included php files, using a text editor that provided an option to use the "Encode in UTF-8 without BOM" encoding. For more info on the php side, see How to avoid echoing character 65279 in php?
就我而言,我能够通过打开和保存所有包含的 php 文件在源代码处修复此问题,使用文本编辑器提供了使用“无 BOM 的 UTF-8 编码”编码的选项。有关 php 方面的更多信息,请参阅如何避免在 php 中回显字符 65279?
回答by Exile3daime
It usually is because of some warning message throwing out from your server without putting it in the response array. For example in PHP, some "warning messages" are not caught in your array so that when you finally use "echo json_encode($RESPONSE_ARR)," it is not a JSON format.
这通常是因为一些警告消息从您的服务器中抛出,而没有将其放入响应数组中。例如,在 PHP 中,一些“警告消息”不会在您的数组中捕获,因此当您最终使用“echo json_encode($RESPONSE_ARR)”时,它不是 JSON 格式。
回答by gnasher729
The JSON that you posted looks Ok. If that is what your iOS application received, it would get parsed. Even if it wasn't Ok, you wouldn't get this error message. JSON must start with '[' if it is an array, and '{' if it is a dictionary like yours, and everything else you get the error message that you got. So even if you sent '[934knsdf239][@@@' you wouldn't get thiserror message, because the data starts with the [ indicating an array.
您发布的 JSON 看起来不错。如果这是您的 iOS 应用程序收到的内容,它将被解析。即使它不是 Ok,您也不会收到此错误消息。JSON 必须以 '[' 开头,如果它是一个数组,'{' 如果它是一个像你这样的字典,其他一切你都会得到你得到的错误消息。因此,即使您发送了 '[934knsdf239][@@@' 您也不会收到此错误消息,因为数据以 [ 开头,表示一个数组。
You need to debug this in the iOS application. First convert the data to a string and print that and check it. If the string looks alright then print the data itself - sometimes people manage to add 0 bytes or control characters, or two byte order markers or something similar which are invisible in the string but are not legal JSON.
您需要在 iOS 应用程序中对此进行调试。首先将数据转换为字符串并打印并检查它。如果字符串看起来没问题,则打印数据本身 - 有时人们会设法添加 0 字节或控制字符,或两个字节顺序标记或类似的东西,它们在字符串中不可见但不是合法的 JSON。
The option NSJSONReadingAllowFragments allows JSON that consists just of a string, number, boolean or null value. Don't use this unless you want to be able to process one of these on its own.
选项 NSJSONReadingAllowFragments 允许仅包含字符串、数字、布尔值或空值的 JSON。除非您希望能够自己处理其中之一,否则不要使用它。
回答by Gurjinder Singh
I faced the same problem. But I found that the Url I was sending as a param to server was wrong. There was a little one character mistake. For example I was sending the below url
我遇到了同样的问题。但是我发现我作为参数发送到服务器的 URL 是错误的。有一个小字符错误。例如我正在发送以下网址
URL = https://somerUrl/api/v2/&venues/search?client_id=jkdasljf3242jka-fsdf-fadsfasd&lat=40.712488&long=-74.006277&distance=25
The mistake was extra & symbol in front of venues making trouble. So i removed & symbol and found worked for me. So, make sure you are sending the correct param to server.
这个错误是在场馆前制造麻烦的额外符号。所以我删除了 & 符号并发现对我有用。因此,请确保您将正确的参数发送到服务器。
回答by AshvinGudaliya
The problem comes from response parsing. You are trying to de-serialize a JSON response (which MUST be contained in either an NSArray
or NSDictionary
) however your response is none of the above (Most likely a simple string).
问题来自响应解析。您正在尝试反序列化 JSON 响应(必须包含在 anNSArray
或 中NSDictionary
),但是您的响应不是上述任何一个(很可能是一个简单的字符串)。
You can try to Print out your server response. Please use the code in your catch block like. and identifying an error in server side or not.
您可以尝试打印出您的服务器响应。请使用您的 catch 块中的代码。并识别服务器端是否存在错误。
Your server data is not proper JSON format then print out your server data and check a server data is valid or not.
您的服务器数据不是正确的 JSON 格式,然后打印出您的服务器数据并检查服务器数据是否有效。
URLSession.shared.dataTask(with: url) { (data, response, error) in
if let jsonData = data {
do {
let parsedData = try JSONSerialization.jsonObject(with: jsonData, options: .mutableLeaves) as! [String: AnyObject]
}
catch let err{
print("\n\n===========Error===========")
print("Error Code: \(error!._code)")
print("Error Messsage: \(error!.localizedDescription)")
if let data = data, let str = String(data: data, encoding: String.Encoding.utf8){
print("Server Error: " + str)
}
debugPrint(error)
print("===========================\n\n")
debugPrint(err)
}
}
else {
debugPrint(error as Any)
}
}.resume()