iOS JSON Error: NSDebugDescription=Garbage at end

半城伤御伤魂 提交于 2019-11-29 15:30:27

encoding is very important. If your json is valid, the issue might be you have special characters in your json data, which is not correctly parsed by the json serializer. When you send the data, make sure you have the correct url-encoding when sending content so client will parse it correctly. Using utf-8 always or base64.

I was able to solve the same problem (works on wifi, but not on carrier network) by sending a content-length header just before the response:

header("Content-length: ".strlen($response));
echo $response;
exit;

I ended up having to change my php file from echoing the json syntax to simply outputting with json_encode.

JsonData is usually stored in dictionary format. Since the json is not able to parse the continuous data[its not able to separate the responses] its throwing this error .

You can maintain a dictionary to store the responses obtained from server . Each task will have a unique response . So create a dictionary with "keys" as "taskIdentifier" of tasks and "values" as "data".

Eg: Inside didReceiveData or any other equivalent methods [where you get response from server ] store response in dictionary with taskIdentifier as keys .

 NSString *taskID = [@(dataTask.taskIdentifier) stringValue];
[_task_data_dictionary setObject:data forKey:taskID];

Here _task_data_dictionary is the dictionary.In this way you can get rid of the above error .

After this you can get data using the same dictionary using this code

 NSData *data = [_task_data_dictionary objectForKey:taskNumber];

again using the taskIdentifier .

Hope this helps .

using swift 4, first of all check the JSON Data using print :

print (String(data:data!, encoding: .utf8)!)

check for the white spaces or unwanted characters, then remove them :

var string = String(data: data!, encoding: .utf8)
string = string?.replacingOccurrences(of: "/r/n", with: "")

after that, assign the string back to data variable :

let data1 = string!.data(using: .utf8)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!