[英]How can I parse JSON to convert this to an array of objects in Swift?
這是我網站上的 json 示例:
[{
"id": "1",
"day": "Saturday 3/10",
"title": "title1",
"description": "lorem ipsum dolor sit amet consectetur adipiscing elit",
"image": ""
},
{
"id": "2",
"day": "Saturday 10/10",
"title": "title2",
"description": "lorem ipsum dolor sit amet consectetur adipiscing elit",
"image": ""
},
{
"id": "3",
"day": "Saturday 17/10",
"title": "title3",
"description": "lorem ipsum dolor sit amet consectetur adipiscing elit",
"image": ""
}]
現在我想將每個對象保存在一個對象數組中,但可能有三個以上的元素。 我想我必須使用NSJsonSerialization
因為我必須從 url 中獲取它。
(我正在使用 swift 2)
在 Swift 4.x 中有一種簡單的方法可以做到這一點,但我很難找到簡單的答案,所以我會把它貼在這里。
第 1 步:創建一個與您的 JSON 匹配並派生自 Codable 的類。 在這里,我隨意將該類(包裝您的原始 JSON)命名為BlogPost
。
您還需要添加一個 init 方法
class BlogPost : Codable{
var id : Int
var day : Date
var title : String
var description : String
init (id : Int, day : Date, title : String, description : String){
self.id = id;
self.day = day;
self.title = title;
self.description = description;
}
}
第 2 步:添加一個加載數組的加載方法。
它將獲取一個文件名(指向帶有 json 的文件)並返回一個 BlogPost 數組([BlogPost])
func loadJson(filename fileName: String) -> [BlogPost]? {
if let url = Bundle.main.url(forAuxiliaryExecutable: fileName) {
do {
let data = try Data(contentsOf: url)
let decoder = JSONDecoder()
let allBlogPosts = try decoder.decode([BlogPost].self, from: data)
return allBlogPosts
} catch {
print("error:\(error)")
}
}
return nil
}
}
我認為棘手的部分是您發送給解碼器方法的類型。 因為我們想要解碼我們必須使用的 Decodable BlogPost 對象數組: [BlogPost].self
decoder.decode([BlogPost].self, from: data)
我個人會使用 NSArrays 和 NSDictionaries 來引用 JSON 中的每個對象。 這樣的東西就足夠了(讓JSON
成為你的 JSON 變量)
if let array = JSON as? NSArray {
for obj in array {
if let dict = obj as? NSDictionary {
// Now reference the data you need using:
let id = dict.valueForKey("id")
}
}
}
這對我有用:
if let JSONData = try? Data(contentsOf: url!) {
do {
let parsed = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as? NSArray
for obj in parsed! {
let obj = MyObject(json: obj as! NSDictionary)
list.append(obj)
}
} catch let parseError {
print(parseError)
}
}
另一種方法是使用https://github.com/Hearst-DD/ObjectMapper ,您可以輕松地從 JSON 生成對象並將它們轉換回 JSON
class Event: Mappable {
var id:String?
var day:String?
var title:String?
var description:String?
var image:String?
required init?(map: Map){
}
func mapping(map: Map) {
id <- map["id"]
day <- map["day"]
title <- map["title"]
description <- map["description"]
image <- map["image"]
}
}
// make event from JSON
let event = Mapper<Event>().map(JSON)
// to JSON
event.toJSON()
只是一個簡單的例子,我希望這會對某人有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.