【问题标题】:How to read dictionary list from socket connection?如何从套接字连接中读取字典列表?
【发布时间】:2015-04-20 13:41:10
【问题描述】:

从表单的套接字数据中读取字典的正确方法是什么:

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

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

【问题讨论】:

    标签: ios objective-c json swift nsdictionary


    【解决方案1】:

    假设您已经将字符串字典放入字典中:

    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,而不是应用无聊和自定义的解析。

    【讨论】:

    • 请仔细看数据。格式是 {}{}{} 在另一层。现在的挑战是将其作为字典数组读取,而不需要破解。
    • 那么,当你接受请求时,响应是一个字符串“json-fake”,就像你发布的字符串一样?
    • 读取数据没有问题。格式化是一个挑战。我要做的是将上述数据转换为以下格式 [{"data": {"abc": [], "pqr": []}, "error": ""}, {"data" :{“abc”:[],“pqr”:[]},“错误”:“”},{“数据”:{“abc”:[],“pqr”:[]},“错误”: ""}] 。仔细注意大括号。
    • 这不会解决问题,因为我们无法区分两个字典。它仍将被视为一个对象而不是列表。
    • 如果你使用的是socket,那么上面推荐的json格式就不能使用了,因为我们在chucks中获取了大量的数据,而且每个都是json。
    【解决方案2】:
    var dictionary = ["key" : "value", "key1" : "value1", "key2" : "value2", "Key3" : "Value3"]
    
    for (key, value) in companies 
    {
        println("\(value)")
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-29
      • 1970-01-01
      • 2021-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多