简体   繁体   English

在 Swift 中将 JSON 对象解码为纯字符串

[英]Decode JSON object to plain String in Swift

Context语境

This is a follow-up question to that question I asked a few days ago, reading it beforehand is not strictly necessary though.这是我几天前问的那个问题的后续问题,不过,事先阅读它并不是绝对必要的。

I have an API endpoint /common , returning JSON data in that form:我有一个 API 端点/common ,以这种形式返回 JSON 数据:

{
    "data":
    {
        "players": [
        {
            "id": 1,
            "name": "John Doe"
        },
        {
            "id": 15,
            "name": "Jessica Thump"
        }],
        "games": [
        {
            "name": "Tic Tac Toe",
            "playerId1": 15,
            "playerId2": 1
        }]
    }
}

In further code snippets, it is assumed that this response is stored as a String in the variable rawApiResponse .在进一步的代码片段中,假设此响应作为String存储在变量rawApiResponse

My aim is to decode that to according Swift struct s:我的目标是根据 Swift struct s对其进行解码:

struct Player: Decodable {
    var id: Int
    var name: String?
}

struct Game: Decodable {
    var name: String
    var player1: Player
    var player2: Player
    
    enum CodingKeys: String, CodingKey {
        case name
        case player1 = "playerId1"
        case player2 = "playerId2"
    }
}

Thanks to the answer in my original question, I can now decode Player s and Game s successfully, but only when the response String I use is the inner array, eg :感谢我原来问题中的答案,我现在可以成功解码Player s 和Game s,但只有当我使用的响应String是内部数组时, eg

let playersResponse = """
[
    {
        "id": 1,
        "name": "John Doe"
    },
    {
        "id": 15,
        "name": "Jessica Thump"
    }
]
"""

let players = try! JSONDecoder().decode([Player].self, from: playersResponse.data(using: .utf8)!)

The question问题

How can I extract only the JSON "players" array from /common 's API response, so that I can feed it afterwards to a JSON decoder for my Player s?如何仅从/common的 API 响应中提取 JSON "players"数组,以便之后可以将其提供给我的Player的 JSON 解码Player

Please note that I can't use (or that's at least what I think) the "usual" Decodable way of making a super- Struct because I need players to be decoded before games (that was the topic of the original question).请注意,我不能使用(或者至少我认为是这样)制作超级Struct的“通常”可Decodable方式,因为我需要在games前对players进行解码(这是原始问题的主题)。 So, this doesn't work:所以,这不起作用:

struct ApiResponse: Decodable {
    let data: ApiData
}

struct ApiData: Decodable {
    let players: [Player]
    let games: [Game]
}
let data = try! JSONDecoder().decode(ApiResponse.self, from: rawApiResponse.data(using: .utf8)!)

What I tried so far到目前为止我尝试过的

I looked into how to convert a JSON string to a dictionary but that only partially helped:我研究了如何将 JSON 字符串转换为字典,但这只是部分帮助:

let json = try JSONSerialization.jsonObject(with: rawApiResponse.data(using: .utf8)!, options: .mutableContainers) as? [String:AnyObject]
let playersRaw = json!["data"]!["players"]!!

If I dump playersRaw , it looks like what I want, but I have no clue how to cast it to Data to pass it to my JSONDecoder , as type(of: playersRaw) is __NSArrayM .如果我转储playersRaw ,它看起来像我想要的,但我不知道如何将它转换为Data以将它传递给我的JSONDecoder ,因为type(of: playersRaw)__NSArrayM


I feel like I'm not doing things the way they should be done, so if you have a more "Swifty" solution to the general problem (and not specifically to how to extract a subset of the JSON data), it would be even nicer!我觉得我没有按照他们应该做的方式做事,所以如果你有一个更“Swifty”的解决方案来解决一般问题(而不是专门针对如何提取 JSON 数据的子集),它甚至更好!

You can make that happen by implementing the decoding yourself in ApiData and searching for each player id in the players array:您可以通过在ApiData自己实现解码并在players数组中搜索每个玩家 ID 来实现这一点:

struct ApiResponse: Decodable {
    let data: ApiData
}

struct ApiData: Decodable {
    let players: [Player]
    var games: [Game]
    
    enum CodingKeys: String, CodingKey {
        case players
        case games
    }
    
    enum GameCodingKeys: String, CodingKey {
        case name
        case playerId1
        case playerId2
    }
    
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        
        players = try container.decode([Player].self, forKey: .players)
        var gamesContainer = try container.nestedUnkeyedContainer(forKey: .games)
        games = []
        while !gamesContainer.isAtEnd {
            let gameContainer = try gamesContainer.nestedContainer(keyedBy: GameCodingKeys.self)
            let playerId1 = try gameContainer.decode(Int.self, forKey: .playerId1)
            let playerId2 = try gameContainer.decode(Int.self, forKey: .playerId2)
            guard
                let player1 = players.first(where: { $0.id == playerId1 }),
                let player2 = players.first(where: { $0.id == playerId2 })
            else { continue }
            let game = Game(
                name: try gameContainer.decode(String.self, forKey: .name),
                player1: player1,
                player2: player2
            )
            games.append(game)
        }
    }
}

struct Player: Decodable {
    var id: Int
    var name: String?
}

struct Game: Decodable {
    var name: String
    var player1: Player
    var player2: Player
}

It's a little ugly, but in the end you can use it like this:有点难看,但最后你可以这样使用它:

let decoder = JSONDecoder()
do {
    let response = try decoder.decode(ApiResponse.self, from: rawApiResponse.data(using: .utf8)!)
    let games = response.data.games
    print(games)
} catch {
    print(error)
}

You just need to provide a root structure and get its data players.您只需要提供一个根结构并获取其数据播放器。 No need to decode the values you don't want:无需解码您不想要的值:


struct ApiResponse: Decodable {
    let data: ApiData
}

struct ApiData: Decodable {
    let players: [Player]
    let games: [Game]
}

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

struct Game: Decodable {
    var name: String
    var player1: Int
    var player2: Int
    enum CodingKeys: String, CodingKey {
        case name, player1 = "playerId1", player2 = "playerId2"
    }
}

let common = """
{
    "data":
    {
        "players": [
        {
            "id": 1,
            "name": "John Doe"
        },
        {
            "id": 15,
            "name": "Jessica Thump"
        }],
        "games": [
        {
            "name": "Tic Tac Toe",
            "playerId1": 15,
            "playerId2": 1
        }]
    }
}
"""

do {
    let players = try JSONDecoder().decode(ApiResponse.self, from: Data(common.utf8)).data.players
    print(players)  // [__lldb_expr_48.Player(id: 1, name: "John Doe"), __lldb_expr_48.Player(id: 15, name: "Jessica Thump")]
    let games = try JSONDecoder().decode(ApiResponse.self, from: Data(common.utf8)).data.games
    print(games)  // [__lldb_expr_52.Game(name: "Tic Tac Toe", player1: 15, player2: 1)]
    
    // or get the common data
    let commonData = try JSONDecoder().decode(ApiResponse.self, from: Data(common.utf8)).data
    print(commonData.players)
    print(commonData.games)
} catch {
    print(error)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM