我想解析具有以下格式的JSON:
{
"list": {
"q": "cookie",
"sr": "28",
"ds": "any",
"start": 0,
"end": 50,
"total": 6536,
"group": "",
"sort": "r",
"item": [
{
"offset": 0,
"group": "Branded Food Products Database",
"name": "THE COOKIE DOUGH CAFE, GOURMET EDIBLE COOKIE DOUGH, COOKIES & CREAM, UPC: 850947006012",
"ndbno": "45095905",
"ds": "BL"
},
{
"offset": 1,
"group": "Branded Food Products Database",
"name": "MELK AND COOKIES, COOKIE DOUGH CLUSTERS CHOCOLATE CHIP COOKIES, UPC: 094922378675",
"ndbno": "45026487",
"ds": "BL"
}]
}
我想在两个类中获取数据。我在JSON文件中获得的项目和列表中的项目的一个类。
item类应该有变量offset,group,name,ndbno和ds。然后我想把所有项目都放到一个数组“items”。
类列表将包含变量q,sr,ds,start,end,total,group,sort和数组项。
我想在我定义的类结构中使用json结构。
有人知道怎么做吗?感谢。
我从网站上获取了json。我收到的请求包含以下代码:
//Send Request
var done = false
print("Send request")
var requestResponse = ""
var parsedResults: AnyObject?
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {// check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {// check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
}
let responseString = String(data: data, encoding: .utf8)
done = true
requestResponse = responseString!
//print("responseString = \(responseString)")
}
task.resume()
//Wait for response
repeat {
RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.1))
} while !done
答案 0 :(得分:2)
在Swift 4中非常简单
let jsonString = """
{
"list": {
"q": "cookie",
"sr": "28",
"ds": "any",
"start": 0,
"end": 50,
"total": 6536,
"group": "",
"sort": "r",
"item": [
{
"offset": 0,
"group": "Branded Food Products Database",
"name": "THE COOKIE DOUGH CAFE, GOURMET EDIBLE COOKIE DOUGH, COOKIES & CREAM, UPC: 850947006012",
"ndbno": "45095905",
"ds": "BL"
},
{
"offset": 1,
"group": "Branded Food Products Database",
"name": "MELK AND COOKIES, COOKIE DOUGH CLUSTERS CHOCOLATE CHIP COOKIES, UPC: 094922378675",
"ndbno": "45026487",
"ds": "BL"
}
]
}
}
"""
struct Root : Decodable {
let list : List
struct List : Decodable {
let q : String
let sr : String
let ds : String
let start : Int
let end : Int
let total : Int
let group : String
let sort : String
let item : [Item] // should be `items`
struct Item : Decodable {
let offset : Int
let group : String
let name : String
let ndbno : String
let ds : String
}
}
}
let data = Data(jsonString.utf8)
do {
let result = try JSONDecoder().decode(Root.self, from: data)
print(result)
} catch { print(error) }
PS:正如评论中已经提到的:while循环很糟糕。使用异步完成处理程序