首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Swift 4.1中使用JSON Decodable

在Swift 4.1中使用JSON Decodable
EN

Stack Overflow用户
提问于 2018-11-13 16:15:16
回答 2查看 144关注 0票数 -6
代码语言:javascript
复制
{  
    "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?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-11-13 16:45:03

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

尽可能地声明结构成员是非可选的。URL可以被解码为URL

代码语言:javascript
复制
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]?
}

现在解码

代码语言:javascript
复制
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let result = try decoder.decode(Root.self, from: data)
self.recipes = result.recipes
票数 0
EN

Stack Overflow用户

发布于 2018-11-13 16:30:53

以下是您的JSON的模型:

代码语言:javascript
复制
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可解码的代码:

代码语言:javascript
复制
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)
}
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53276566

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档