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



例如

{

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

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

数字 = 1

人 = " { "名字": "杰森", "年龄" : 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

试试这个....

如果您想在字符串中获得响应,请尝试此操作...

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

相关内容

  • 没有找到相关文章

最新更新