如何从swift4中的json数组获取值

时间:2019-03-05 13:30:38

标签: ios json swift iphone

我无法将json值转换为变量。我正在打印值,但问题是没有数组我无法获得json值

这是我的json

{
"Categories": [
    "city",
    "delhi"
   ]
}

我想用数组对值进行即时分类,用数组来打印值

这是我的代码

do{
            let json = try JSONSerialization.jsonObject(with: data!, options: []) as! [String: AnyObject]
            print(json as AnyObject)

            if let Categories = json["Categories"] {
                print(Categories)
            }

4 个答案:

答案 0 :(得分:0)

您需要

 do {

     let json = try JSONSerialization.jsonObject(with: data!, options: []) as! [String:[String]]
      let arr1 = json["Categories"]!
      let str1 =  arr1.joined(separator: ":")
       print(str1)
     // or 
      let decoded = try JSONDecoder().decode(Root.self, from: data)
       let str =  decoded.categories.joined(separator: ":")
       print(str)

 } catch {
     print(error)
 }

或使用

struct Root: Codable {
    let categories: [String] 
    enum CodingKeys: String, CodingKey {
        case categories = "Categories"
    }
}

答案 1 :(得分:0)

List<TextSpan> getSpan() { List<TextSpan> spans = List<TextSpan>(); spans.add(TextSpan( text: "And thus We made them rise ", )); spans.add( TextSpan( text: " they ", style: TextStyle( decoration: TextDecoration.underline, ), recognizer: TapGestureRecognizer() ..onTap = () { print("click on me"); }), ); spans.add(TextSpan( text: " And thus We made them rise ", )); return spans; } 使您的生活更轻松。首先为您的响应创建自定义模型

Codable

然后使用struct Response: Decodable { let categories: [String] enum CodingKeys: String, CodingKey { case categories = "Categories" } } 解码收到的data

JSONDecoder

答案 2 :(得分:0)

使用内置的swift支持,通过遵循Decodable和json CustomStringConvertible来解码json,以获取值的字符串表示形式

struct Item: Decodable, CustomStringConvertible {
    let categories: [String]

    enum CodingKeys: String, CodingKey {
        case categories = "Categories"
    }

    public var description: String {
        return categories.joined(separator: " ")
    }
}

let decoder = JSONDecoder()
do {
    let result = try decoder.decode(Item.self, from: data)
    let descr = result.description
    print(descr)
} catch {
    print(error)
}

答案 3 :(得分:0)

//Model Class should be like this
struct JsonResposne : Codable {

    let categories : [String]?

    enum CodingKeys: String, CodingKey {
            case categories = "Categories"
    }

    init(from decoder: Decoder) throws {
            let values = try decoder.container(keyedBy: CodingKeys.self)
            categories = try values.decodeIfPresent([String].self, forKey: .categories)
    }

}

func getCategoriesResponse() {

Alamofire.request(requestUrl, method: .post, parameters: params, encoding: URLEncoding.default).responseJSON { (response) in
        switch response.result {
        case .success:
            if response.data != nil {
                do {
        let decoder = JSONDecoder()
        let apiResponse:JsonResponse = try decoder.decode(JsonResponse.self, from: responseData)
        print(apiResponse.categories.count)

    }catch {
        print(error.localizedDescription)
    }
                }
            }
            break
        case .failure:
            print("There was something with your call")
            break
        }
    }

}