ios - Swift - 解析某些数据

标签 ios json swift parsing

需要从下面的API响应中提取desc的数据。我需要从中提取每个 ab,以便我可以将其用于数学加法应用程序。

data from the server

 [
    {
        "id": 226,
        "name": "chorename",
        "desc": "{\n  \"questions\" : [\n    {\n      \"b\" : 2,\n      \"a\" : 1\n    },\n    {\n      \"b\" : 3,\n      \"a\" : 2\n    },\n    {\n      \"b\" : 2,\n      \"a\" : 8\n    },\n    {\n      \"b\" : 9,\n      \"a\" : 7\n    },\n    {\n      \"b\" : 3,\n      \"a\" : 6\n    }\n  ],\n  \"operation\" : \"addition\"\n}",
        "reward": "1.00",
        "sched": "2018-04-19T15:54:24.657644+08:00",
        "parent": "shit",
        "type": "homework",
        "child": "",
        "occurrence": {
            "name": "once"
        },
        "status": {
            "name": "ongoing"
        },
        "date_created": "2018-04-23T14:16:35.739436+08:00",
        "date_modified": "2018-04-23T14:16:35.790237+08:00"
    }
]
code on getting request
func demoApi1() {
        Alamofire.request("", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in

            switch(response.result) {
            case .success(_):
                guard let json = response.result.value as! [[String:Any]]? else{ return}
                print("Ang Response: , \(json)")

                for item in json {

                    var a = self.getAllDetail.append(item )
                    print("shit:" , a)


                    // if let title = item["title"] as? String {
                    //   self.titleArray.append(title)
                    // }

                }
                if !self.getAllDetail.isEmpty{
                    DispatchQueue.main.async {

                    }
                }
                break

            case .failure(_):
                print("Error")
                break

            }
        }

    }

let devices = assign "a" here
        let randomIndex = Int(arc4random_uniform(UInt32(devices.count)))
        let randomItem = devices[randomIndex]
        print("random item:" ,randomItem)


        let device2 = //assign "b" here
        let randomIndex1 = Int(arc4random_uniform(UInt32(devices.count)))
        let randomItem1 = device2[randomIndex]

API 响应:

 Ang Response [["status": {
    name = ongoing;
}, "sched": 2018-04-10T14:22:00+08:00, "desc": asdasdasdsa, "id": 224, "reward": 1.00, "parent": das, "child": dasdas, "date_created": 2018-04-19T15:54:24.657644+08:00, "name": sad, "occurrence": {
    name = once;
}, "type": , "date_modified": 2018-04-19T15:54:24.703520+08:00], ["status": {
    name = ongoing;
}, "sched": 2018-04-19T15:54:24.657644+08:00, "desc": {
  "questions" : [
    {
      "b" : 2,
      "a" : 1
    },
    {
      "b" : 3,
      "a" : 2
    },
    {
      "b" : 2,
      "a" : 8
    },
    {
      "b" : 9,
      "a" : 7
    },
    {
      "b" : 3,
      "a" : 6
    }
  ],
  "operation" : "addition"
}, "id": 226, "reward": 1.00, "parent": shit, "child": , "date_created": 2018-04-23T14:16:35.739436+08:00, "name": chorename, "occurrence": {
    name = once;
}, "type": homework, "date_modified": 2018-04-23T14:16:35.790237+08:00]]

最佳答案

下面的代码可用于将json字符串字符串转换为字典

Objective-c

+ (NSDictionary *)dictionaryFromJSONString:(NSString *)jsonString
{
    // @"{\"2\":\"3\"}"
    NSError *jsonError;
    NSData *objectData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
                                                         options:NSJSONReadingMutableContainers
                                                           error:&jsonError];
    return json;
}

SWIFT

func getDictionaryFromString(_ jsonString: String) -> [String:Any]? {

        let objectData = jsonString.data(using: .utf8)
        var dict: [String:Any]?

        if objectData != nil {
            do {
                dict = try JSONSerialization.jsonObject(with: objectData!, options:  .allowFragments) as? [String : Any]

            } catch {
                print("Error occured.")
            }
        }
        return dict
    }

创建字典后,您可以通过键访问值。

关于ios - Swift - 解析某些数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49974634/

相关文章:

ios - 有 2 个 textField.delagate = self 取消其中一个

ios - 在 IOS 上的 React Native 上找不到 RCTConvert+AirMap.h 文件错误

iphone - NSMutableArray 难度

json - 您可以在 Avro JSON 模式文件中添加注释吗?

swift - 如何使用 Vapor (流畅迁移)将字段从必需更新为可选?

ios - 删除弹出 View Controller -swift

ios - 单击Xco​​de 4.3.3时,保持按钮突出显示

ios - 方向更改后如何避免调整 UITableView(旋转)单元格的大小?

jquery - 动态定义 jqGrid

javascript - 数据键函数过滤器始终返回第一个元素