【问题标题】:how to get value from json array in swift4如何从swift4中的json数组中获取值
【发布时间】:2019-07-26 23:50:32
【问题描述】:

我无法将 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)
            }

【问题讨论】:

  • 尝试通过 pods 使用 swiftyjson

标签: ios json swift iphone


【解决方案1】:

你需要

 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"
    }
}

【讨论】:

  • 用数组打印我想在没有数组的情况下显示
【解决方案2】:

Codable 让您的生活更轻松。首先为您的响应创建自定义模型

struct Response: Decodable {

    let categories: [String]

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

然后解码您使用JSONDecoder接收的data

if let data = data {
    do {
        let decoded = try JSONDecoder().decode(Response.self, from: data)
        let string = decoded.categories.joined(separator: ", ") // if u need to join 
                                                                // your array to 
                                                                // single `String`
        print(string)
    } catch { print(error) }
}

【讨论】:

  • 它没有数组,但我想将该值放入变量中
【解决方案3】:

通过符合Decodable 并同时符合CustomStringConvertible 来使用内置的 swift 支持解码 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)
}

【讨论】:

    【解决方案4】:
    //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
            }
        }
    

    }

    【讨论】:

      猜你喜欢
      • 2023-04-03
      • 1970-01-01
      • 2021-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-30
      • 1970-01-01
      相关资源
      最近更新 更多