gpt4 book ai didi

php - json 解析失败 - cocoa 错误 3840 和字符 0 周围的无效值

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:17:13 27 4
gpt4 key购买 nike

我知道有很多问题都解决了这个问题,但我还没有找到对我有帮助的...

当我解析从本地主机(MAMP 服务器)下载的 json 数据时,我遇到 json 错误 3840,指出字符 0 周围的值无效...

我不明白为什么,因为我的 php 脚本在我的数组上显示了一个 var_dump(数组的数组):

array(2) { [0]=> array(5) { ["ID"]=> string(1) "1" ["EDS"]=> string(4) "1000" ["lastname"]=> string(8) "My lastname" ["firstname"]=> string(9) "My firstname" ["dateOfBirth"]=> string(10) "19.12.1975" } [1]=> array(5) { ["ID"]=> string(1) "2" ["EDS"]=> string(4) "1001" ["lastname"]=> string(14) "Smith" ["firstname"]=> string(6) "John" ["dateOfBirth"]=> string(10) "11.11.1111" } }     

...这对我来说似乎是一个有效的 json 数组。

当我记录下载的 NSMutableData 时,它不是空的,而是类似于

76353648 2734b0a9 (+ around fifty like this).

不知道是不是因为数据不全,不知道怎么继续往下分析到底哪里出了问题。

如果有人知道会发生什么(我知道这与无法识别的特殊字符有关),那就太好了。

非常感谢!

编辑:为原始问题添加后续代码:

(void)connectionDidFinishLoading:(NSURLConnection *)connection {
id jsonObject = [NSJSONSerialization JSONObjectWithData:_downloadedData options:NSJSONReadingAllowFragments error:&error];

if ([jsonObject isKindOfClass:[NSArray class]]) {

NSArray *deserializedArray = (NSArray *)jsonObject;

for (NSDictionary *jsonElement in deserializedArray)
{
Person *newPersonElement = [[PersonStore sharedStore] createPerson]; // --> what makes the app crash. But this method is working everywhere else...
// more code omitted
}

我不知道为什么这个初始化会在这里崩溃......

最佳答案

更新的答案:

我认为既然您已经发布了使用此接收到的 JSON 的 Objective-C 代码,那么实际问题是什么就变得很清楚了。

在我看来,您正在使用 Core Data (PersonStore) 来保存传入的数据。

如果您从调用 connectionDidFinishLoading: 的同一线程调用 Core Data,您很可能会遇到线程问题,Core Data 不高兴您从主线程以外的线程。

试一试:在您的 connectionDidFinishLoading: 中将您的代码包装在以下内容中:

dispatch_async(dispatch_get_main_queue(), ^{
// Include the code here that walks over the incoming JSON
// and creates new `Person` instances.
});

这将在主线程上执行该 block 中的所有内容。这通常是核心数据使用的好主意。 (甚至可能需要,查看文档,如果我没记错的话,有一个关于核心数据和线程的特殊部分)。

很好奇这是否有效。

旧答案:

vardump 的输出实际上不是有效的 JSON。您需要改用 json_encode() 函数。

您可以通过执行以下操作将从服务器接收到的 NSData 转换为字符串:

if let s = String(data: data, encoding: NSUTF8StringEncoding) {
println(s)
}

您没有提到您是在 Swift 还是 Objective-C 中工作,但以上内容很容易转换为 Objective-C。

关于php - json 解析失败 - cocoa 错误 3840 和字符 0 周围的无效值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28909723/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com