在Swift 4.1中使用JSON可解码

时间:2018-11-13 08:15:16

标签: json swift

{  
    "count":30,
    "recipes":[  
        {  
            "publisher":"Closet Cooking",
            "f2f_url":"http://food2fork.com/view/35382",
            "title":"Jalapeno Popper Grilled Cheese Sandwich",
            "source_url":"http://www.closetcooking.com/2011/04/jalapeno-popper-grilled-cheese-sandwich.html",
            "recipe_id":"35382",
            "image_url":"http://static.food2fork.com/Jalapeno2BPopper2BGrilled2BCheese2BSandwich2B12B500fd186186.jpg",
            "social_rank":100.0,
            "publisher_url":"http://closetcooking.com"
        }
    ]
}

请问如何使用Swift 4.1 Decodable解析此JSON?

2 个答案:

答案 0 :(得分:0)

您的previous question非常接近,但是您必须为根对象添加结构

尽可能声明结构成员为非可选。网址可以解码为URL

struct Root : Decodable {
    let count : Int 
    let recipes : [Recipe]
}

struct Recipe : Decodable { // It's highly recommended to declare Recipe in singular form
    let recipeId : String
    let imageUrl, sourceUrl, f2fUrl : URL
    let title : String
    let publisher : String
    let socialRank : Double
    let page : Int?
    let ingredients : [String]?
}

现在解码

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let result = try decoder.decode(Root.self, from: data)
self.recipes = result.recipes

答案 1 :(得分:-1)

以下是您的JSON的模型:

struct Recipe: Codable{
    let publisher: String
    let f2f_url: String
    let title: String
    let source_url: String
    let recipe_id: String
    let image_url: String
    let social_rank: Float
    let publisher_url: String
}


struct  Model: Codable {
    let count: Int
    let recipes: [Recipe]
}

及以下是可解码的JSON:

let json = """
{
    "count":30,
    "recipes":[
        {
            "publisher":"Closet Cooking",
            "f2f_url":"http://food2fork.com/view/35382",
            "title":"Jalapeno Popper Grilled Cheese Sandwich",
            "source_url":"http://www.closetcooking.com/2011/04/jalapeno-popper-grilled-cheese-sandwich.html",
            "recipe_id":"35382",
            "image_url":"http://static.food2fork.com/Jalapeno2BPopper2BGrilled2BCheese2BSandwich2B12B500fd186186.jpg",
            "social_rank":100.0,
            "publisher_url":"http://closetcooking.com"
        }
    ]
}
""".data(using: .utf8)!

let decoder = JSONDecoder()

do {
   let model = try decoder.decode(Model.self, from: json) //Decode JSON Response Data
   print(model)
} catch let parsingError {
   print("Error", parsingError)
}