【问题标题】:How can I parse JSON to convert this to an array of objects in Swift?如何解析 JSON 以将其转换为 Swift 中的对象数组?
【发布时间】:2015-12-20 22:36:03
【问题描述】:

这是我网站上的 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,因为我必须从一个网址获取它。

(我正在使用 swift 2)

【问题讨论】:

  • 您是如何尝试这样做的? (随意展示一些代码),你遇到了什么问题?
  • 您的实际问题是什么?
  • 如何将在线 json 文件中的对象保存在数组中
  • 你看过 NSJSONSerialization 吗?

标签: ios json swift


【解决方案1】:

我个人会使用 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")
        }
    }
}

【讨论】:

  • 我认为问题是如何将 JSON 解析为数组和字典——比如通过 NSJSONSerialization
  • 这段代码运行良好,但不是我想要的。但它帮助了我。谢谢!
  • @Cailean Wilkinson 你能解释一下让 JSON 成为你的 JSON 变量吗? JSON 变量的值是多少
【解决方案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
    }

}

我认为棘手的部分是您发送到解码器方法的类型。由于我们要解码一组可解码的 BlogPost 对象,我们必须使用:[BlogPost].self

decoder.decode([BlogPost].self, from: data)

【讨论】:

  • 从 swift 5 开始,您不需要在可编码结构中显式初始化 - 编译器会自动生成它
【解决方案3】:

这对我有用:

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

【讨论】:

    【解决方案4】:

    另一种方法是使用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()
    

    只是简单的例子, 我希望这会对某人有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-18
      • 1970-01-01
      • 1970-01-01
      • 2021-08-14
      • 1970-01-01
      • 2021-06-12
      • 1970-01-01
      相关资源
      最近更新 更多