ios - 如何从套接字连接读取字典列表?

标签 ios objective-c json swift nsdictionary

从以下形式的套接字数据读取字典的正确方法是什么:

{"data": {"abc": [], "pqr": []}, "error": ""}{"data": {"abc": [], "pqr": []}, "error": ""}{"data": {"abc": [], "pqr": []}, "error": ""}{"data": {"abc": [], "pqr": []}, "error": ""}{"data": {"abc": [], "pqr": []}, "error": ""}

注意有独立的 json 字典,我们需要将其转换为字典列表。我们始终可以使用 stringByReplacingOccurrencesOfString 方法通过替换“}{”来做到这一点。但有更好的方法吗?

最佳答案

假设您已经将 string-dictionary 放入字典中:

NSDictionary* jsonSocketData;

for(NSDictionary* data in jsonSocketData[@"data"]) {
   /* whatever */
   NSLog(@"%@", data[@"abc"]); 
}

顺便说一句,我希望您的请求的结果更像是这样:

{
    "result": [
        {
            "data": {
                "abc": [],
                "pqr": []
            },
            "error": ""
        },
        {
            "data": {
                "abc": [],
                "pqr": []
            },
            "error": ""
        }
    ]
}

如果您必须将 NSString (json) 转换为 NSDictionary:

NSString* jsonString = @"..";

NSData* data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

编辑

如果您发布的字符串与您收到的字符串完全相同,我会使用此技巧(这样 json 将格式良好):

NSString* response = @"...";
/* only if you are sure about format */
response = [response stringByReplacingOccurrencesOfString: @"}{" withString:@"},{"];
/* otherwise you can apply regex, defintely more flexible, with pattern "}(.?){" */
response = [NSString stringWithFormat:@"{\"result\":[%@]}", response];

完成此技巧后,您可以应用上面的代码。 顺便说一句,在我看来,最好的方法是拥有格式良好的 json,而不是应用无聊的自定义解析。

关于ios - 如何从套接字连接读取字典列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29749596/

相关文章:

ios - 使用字典中的值更新多个标签?

ios - IOS7和 "Terminated due to Memory Pressure"中的内存管理

ios - UITableView 的第一部分中的标题显示有跳转

json - Javascript从node/express服务器读取gz文件

android - Cordova:android.json 中的 PACKAGE_NAME 是什么意思?

ios - 核心情节: Grid lines appear once per two plots

ios - Swift 5 反射获取类属性列表并调用它们

objective-c - 执行选择器 ARC 警告

ios - 如何弹出 UIImagePickerController 的导航

java - 无法将 JSON 对象发送到 Rest Web 服务