我可以将部分数据提取为可快速解码的字符串吗?

时间:2018-06-29 05:19:09

标签: json swift decodable

例如

{

{
  "data": {
    "number": 1,
    "person": {
      "name": "Jason"
      "age" : 18
    }
  }
}

我想获取数据“人”作为字符串 所以下面是我想做的

数字= 1

人= ” { “ name”:“ Jason”, “年龄”:18 } “

我该怎么办请帮助我

  • 添加

我想要得到这样

public struct temp: Decodable {
  public let number: Int
  public let person: String
  
  enum CodingKeys: String, CodingKey {
    case number, person
  }
  
  public init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    
    number = try container.decode(Int.self, forKey: .number)
    
    ////
    Here is code i want to get string of json 
    ////
    
    }
  }
}

如何从可解码结构的数据中获取字符串json

1 个答案:

答案 0 :(得分:0)

尝试一下...。

如果要获取字符串响应,请尝试此...

let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { 
print("error=\(String(describing: error))")
    return
}

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(String(describing: response))")
        }

        //Here you can convert your response into string...
        let responseString = String(data: data, encoding: .utf8)//Response in String formate
        let dictionary = data
        print("dictionary = \(dictionary)")
        print("responseString = \(String(describing: responseString!))")//I think this is your required string....

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

            //Here you write your json code
            let response2 = [ "data": ["number": 1,"person": ["name": "Jason", "age" : 18]]]

            let data  = response2["data"]
            print(data!) // Output : ["number": 1,"person": ["name": "Jason", "age" : 18]]
            let number = data!["number"]
            print(number!) // Output : 1
            let person = data!["person"]
            print(person!)// Output : ["name": "Jason", "age" : 18]


            //If you want to print name and age 

            let person = data!["person"] as! Dictionary<String,Any>
            print(person)// Output : ["name": "Jason", "age" : 18]
            let name = person["name"]
            print(name!)
            let age = person["age"]
            print(age!)


       } catch let error as NSError {
            print(error)
        }

}