如何在swift中解析嵌套的JSON?

问题描述 投票:0回答:2

我有一个本地 JSON 字符串,我正在尝试解析它,但是当我尝试这样做时,我不断收到错误。我也在嵌套字典中看到了这个错误,但找不到错误。 下面是 JSON 字符串:

let jsonNestedString  = "{\"meta\":{\"page\":1,\"total_pages\":4,\"per_page\":10,\"total_records\" : 38}, \"reweries\":[\"id\":1234,\"name\":\"saintArnold\"},{\"id\":52892,\"name\":\"buffalo bayou\"]}"

我正在通过 Codable 执行此过程,下面是我为此创建的结构:

struct PagedBreweries:Codable{
    struct Meta:Codable{
        let page : Int
        let total_pages:Int
        let per_page:Int
        let total_records: Int
        enum CodingKeys: String, CodingKey{
            case page
            case total_pages
            case per_page
            case total_records
        }
    }
    
    struct Brewery :Codable{
        let id:Int
        let name:String
        
    }
    let meta:Meta
    let breweries :[Brewery]
}

然后该数据被解析为如下函数:

    func jsonNested(){
    let jsonData = jsonNestedString.data(using: .utf8)
    let decoder = JSONDecoder()
    let data  = try! decoder.decode(PagedBreweries.Meta.self, from: jsonData!)
    print(data)
}

当我尝试构建时,我得到的错误出现在 try! 中。

decoder.decode

命令 错误是:

线程 1:致命错误:“尝试!”表达式意外地引发了错误:
Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "page", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "没有与键关联的值 CodingKeys(stringValue: "page", intValue: nil) (“页面”)。”,underlyingError:nil))

谁能提供解决方案吗?

ios json swift codable
2个回答
3
投票

正确的json

{
    "meta": {
        "page": 1,
        "total_pages": 4,
        "per_page": 10,
        "total_records": 38
    },
    "reweries": [{
    "id": 1234,
    "name": "saintArnold"
    },
    {
    "id": 52892,
    "name": "buffalo bayou"
    }
    ]
}

struct Root: Codable {
    let meta: Meta
    let reweries: [Rewery]
}

struct Meta: Codable {
    let page, totalPages, perPage, totalRecords: Int

    enum CodingKeys: String, CodingKey {  // snake case may be used 
        case age = "page"
        case totalPages = "total_pages"
        case perPage = "per_page"
        case totalRecords = "total_records"
    }
}

struct Rewery: Codable {
    let id: Int
    let name: String
}

  let jsonNestedString  = """
    {\"meta\":{\"page\":1,\"total_pages\":4,\"per_page\":10,\"total_records\":38}, \"reweries\":[{\"id\":1234,\"name\":\"saintArnold\"},{\"id\":52892,\"name\":\"buffalo bayou\"}]}
"""

  // or 

let jsonNestedString  = """

{
    "meta": {
        "page": 1,
        "total_pages": 4,
        "per_page": 10,
        "total_records": 38
    },
    "reweries": [{
    "id": 1234,
    "name": "saintArnold"
    },
    {
    "id": 52892,
    "name": "buffalo bayou"
    }
    ]
}


"""

do {

    let jsonData = jsonNestedString.data(using: .utf8)
    let decoder = JSONDecoder()
    let data  = try decoder.decode(Root.self, from: jsonData!)
    print(data)


} catch  {
    print(error)
}

2
投票

JSON 已损坏,您正在解码错误的根对象。

这是使用您的结构进行解码并符合 Swift 命名约定的正确 JSON。

let jsonNestedString = """ {"meta":{"page":1,"total_pages":4,"per_page":10,"total_records" : 38}, "breweries":[{"id":1234,"name":"saintArnold"},{"id":52892,"name":"buffalo bayou"}]} """ struct PagedBreweries : Codable { struct Meta : Codable { let page : Int let totalPages:Int let perPage:Int let totalRecords: Int } struct Brewery : Codable { let id:Int let name:String } let meta:Meta let breweries :[Brewery] } func jsonNested(){ let jsonData = Data(jsonNestedString.utf8) let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase let data = try! decoder.decode(PagedBreweries.self, from: jsonData) print(data) } jsonNested() // Printed result: // PagedBreweries(meta: __lldb_expr_1.PagedBreweries.Meta(page: 1, totalPages: 4, perPage: 10, totalRecords: 38), breweries: [__lldb_expr_1.PagedBreweries.Brewery(id: 1234, name: "saintArnold"), __lldb_expr_1.PagedBreweries.Brewery(id: 52892, name: "buffalo bayou")])
    
© www.soinside.com 2019 - 2024. All rights reserved.