Parsing nested JSON using Codable











up vote
1
down vote

favorite












So I'm trying to parse JSON that looks something like this using Codable in Swift.



{
"abilities": [
{
"ability": {
"name": "chlorophyll",
"url": "https://pokeapi.co/api/v2/ability/34/"
},
"is_hidden": true,
"slot": 3
},
{
"ability": {
"name": "overgrow",
"url": "https://pokeapi.co/api/v2/ability/65/"
},
"is_hidden": false,
"slot": 1
}
],
"name": "SomeRandomName"
}


Now it gets confusing when you're trying to get nested data. Now I'm trying to get the name, which is easy. I'm also trying to get the ability name, this is where its gets complicated for me. After some research this is what I came up with.



class Pokemon: Codable {

struct Ability: Codable {
var isHidden: Bool

struct AbilityObject: Codable {
var name: String
var url: String
}

var ability: AbilityObject

private enum CodingKeys: String, CodingKey {
case isHidden = "is_hidden"
case ability
}
}

var name: String
var abilities: [Ability]
}


Now is there any better way in doing this, or am I stuck doing it like this.










share|improve this question


























    up vote
    1
    down vote

    favorite












    So I'm trying to parse JSON that looks something like this using Codable in Swift.



    {
    "abilities": [
    {
    "ability": {
    "name": "chlorophyll",
    "url": "https://pokeapi.co/api/v2/ability/34/"
    },
    "is_hidden": true,
    "slot": 3
    },
    {
    "ability": {
    "name": "overgrow",
    "url": "https://pokeapi.co/api/v2/ability/65/"
    },
    "is_hidden": false,
    "slot": 1
    }
    ],
    "name": "SomeRandomName"
    }


    Now it gets confusing when you're trying to get nested data. Now I'm trying to get the name, which is easy. I'm also trying to get the ability name, this is where its gets complicated for me. After some research this is what I came up with.



    class Pokemon: Codable {

    struct Ability: Codable {
    var isHidden: Bool

    struct AbilityObject: Codable {
    var name: String
    var url: String
    }

    var ability: AbilityObject

    private enum CodingKeys: String, CodingKey {
    case isHidden = "is_hidden"
    case ability
    }
    }

    var name: String
    var abilities: [Ability]
    }


    Now is there any better way in doing this, or am I stuck doing it like this.










    share|improve this question
























      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











      So I'm trying to parse JSON that looks something like this using Codable in Swift.



      {
      "abilities": [
      {
      "ability": {
      "name": "chlorophyll",
      "url": "https://pokeapi.co/api/v2/ability/34/"
      },
      "is_hidden": true,
      "slot": 3
      },
      {
      "ability": {
      "name": "overgrow",
      "url": "https://pokeapi.co/api/v2/ability/65/"
      },
      "is_hidden": false,
      "slot": 1
      }
      ],
      "name": "SomeRandomName"
      }


      Now it gets confusing when you're trying to get nested data. Now I'm trying to get the name, which is easy. I'm also trying to get the ability name, this is where its gets complicated for me. After some research this is what I came up with.



      class Pokemon: Codable {

      struct Ability: Codable {
      var isHidden: Bool

      struct AbilityObject: Codable {
      var name: String
      var url: String
      }

      var ability: AbilityObject

      private enum CodingKeys: String, CodingKey {
      case isHidden = "is_hidden"
      case ability
      }
      }

      var name: String
      var abilities: [Ability]
      }


      Now is there any better way in doing this, or am I stuck doing it like this.










      share|improve this question













      So I'm trying to parse JSON that looks something like this using Codable in Swift.



      {
      "abilities": [
      {
      "ability": {
      "name": "chlorophyll",
      "url": "https://pokeapi.co/api/v2/ability/34/"
      },
      "is_hidden": true,
      "slot": 3
      },
      {
      "ability": {
      "name": "overgrow",
      "url": "https://pokeapi.co/api/v2/ability/65/"
      },
      "is_hidden": false,
      "slot": 1
      }
      ],
      "name": "SomeRandomName"
      }


      Now it gets confusing when you're trying to get nested data. Now I'm trying to get the name, which is easy. I'm also trying to get the ability name, this is where its gets complicated for me. After some research this is what I came up with.



      class Pokemon: Codable {

      struct Ability: Codable {
      var isHidden: Bool

      struct AbilityObject: Codable {
      var name: String
      var url: String
      }

      var ability: AbilityObject

      private enum CodingKeys: String, CodingKey {
      case isHidden = "is_hidden"
      case ability
      }
      }

      var name: String
      var abilities: [Ability]
      }


      Now is there any better way in doing this, or am I stuck doing it like this.







      json swift






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 10 at 0:40









      Luis F Ramirez

      234




      234
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          1
          down vote



          accepted










          Grab your JSON response and dump it in this site.



          It'll generate these structs without Codable. Add Codable so they look like this:



          struct Pokemon: Codable {
          let abilities: [AbilityElement]
          let name: String

          struct AbilityElement: Codable {
          let ability: Ability
          let isHidden: Bool
          let slot: Int

          struct Ability: Codable {
          let name: String
          let url: String
          }
          }
          }


          For keys with snake_case, you can just declare a JSONDecoder and specify the keyDecodingStrategy as .convertFromSnakeCase. No need to muck around with coding keys if you're just converting from snake case. You only need them if you're renaming keys.



          If you have other situations where you need to create custom coding keys for your responses or alter key names, this page should prove helpful.



          You can dump this in a playground and play around with it:



          let jsonResponse = """
          {
          "abilities": [
          {
          "ability": {
          "name": "chlorophyll",
          "url": "https://pokeapi.co/api/v2/ability/34/"
          },
          "is_hidden": true,
          "slot": 3
          },
          {
          "ability": {
          "name": "overgrow",
          "url": "https://pokeapi.co/api/v2/ability/65/"
          },
          "is_hidden": false,
          "slot": 1
          }
          ],
          "name": "SomeRandomName"
          }
          """

          struct Pokemon: Codable {
          let abilities: [AbilityElement]
          let name: String

          struct AbilityElement: Codable {
          let ability: Ability
          let isHidden: Bool
          let slot: Int

          struct Ability: Codable {
          let name: String
          let url: String
          }
          }
          }

          var pokemon: Pokemon?

          do {
          let jsonDecoder = JSONDecoder()
          jsonDecoder.keyDecodingStrategy = .convertFromSnakeCase
          if let data = jsonResponse.data(using: .utf8) {
          pokemon = try jsonDecoder.decode(Pokemon.self, from: data)
          }
          } catch {
          print("Something went horribly wrong:", error.localizedDescription)
          }

          print(pokemon)





          share|improve this answer























          • Thanks Adrian, that site you provided is very helpful. I also knew you could use the coding strategy from snake case to camel case. Just wanted to practice using the coding keys, in case I wanted to switch the names. So to me it looks the same, so I guess I'm stuck doing it like this. But thank you for that helpful site. :)
            – Luis F Ramirez
            Nov 10 at 4:05










          • Coding keys are a PITA, but sometimes you need to use them. If you’re in a production environment or you’ve got proprietary data, would create your structure the “old fashioned” way, not with that site.
            – Adrian
            Nov 10 at 4:08













          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53235000%2fparsing-nested-json-using-codable%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          1
          down vote



          accepted










          Grab your JSON response and dump it in this site.



          It'll generate these structs without Codable. Add Codable so they look like this:



          struct Pokemon: Codable {
          let abilities: [AbilityElement]
          let name: String

          struct AbilityElement: Codable {
          let ability: Ability
          let isHidden: Bool
          let slot: Int

          struct Ability: Codable {
          let name: String
          let url: String
          }
          }
          }


          For keys with snake_case, you can just declare a JSONDecoder and specify the keyDecodingStrategy as .convertFromSnakeCase. No need to muck around with coding keys if you're just converting from snake case. You only need them if you're renaming keys.



          If you have other situations where you need to create custom coding keys for your responses or alter key names, this page should prove helpful.



          You can dump this in a playground and play around with it:



          let jsonResponse = """
          {
          "abilities": [
          {
          "ability": {
          "name": "chlorophyll",
          "url": "https://pokeapi.co/api/v2/ability/34/"
          },
          "is_hidden": true,
          "slot": 3
          },
          {
          "ability": {
          "name": "overgrow",
          "url": "https://pokeapi.co/api/v2/ability/65/"
          },
          "is_hidden": false,
          "slot": 1
          }
          ],
          "name": "SomeRandomName"
          }
          """

          struct Pokemon: Codable {
          let abilities: [AbilityElement]
          let name: String

          struct AbilityElement: Codable {
          let ability: Ability
          let isHidden: Bool
          let slot: Int

          struct Ability: Codable {
          let name: String
          let url: String
          }
          }
          }

          var pokemon: Pokemon?

          do {
          let jsonDecoder = JSONDecoder()
          jsonDecoder.keyDecodingStrategy = .convertFromSnakeCase
          if let data = jsonResponse.data(using: .utf8) {
          pokemon = try jsonDecoder.decode(Pokemon.self, from: data)
          }
          } catch {
          print("Something went horribly wrong:", error.localizedDescription)
          }

          print(pokemon)





          share|improve this answer























          • Thanks Adrian, that site you provided is very helpful. I also knew you could use the coding strategy from snake case to camel case. Just wanted to practice using the coding keys, in case I wanted to switch the names. So to me it looks the same, so I guess I'm stuck doing it like this. But thank you for that helpful site. :)
            – Luis F Ramirez
            Nov 10 at 4:05










          • Coding keys are a PITA, but sometimes you need to use them. If you’re in a production environment or you’ve got proprietary data, would create your structure the “old fashioned” way, not with that site.
            – Adrian
            Nov 10 at 4:08

















          up vote
          1
          down vote



          accepted










          Grab your JSON response and dump it in this site.



          It'll generate these structs without Codable. Add Codable so they look like this:



          struct Pokemon: Codable {
          let abilities: [AbilityElement]
          let name: String

          struct AbilityElement: Codable {
          let ability: Ability
          let isHidden: Bool
          let slot: Int

          struct Ability: Codable {
          let name: String
          let url: String
          }
          }
          }


          For keys with snake_case, you can just declare a JSONDecoder and specify the keyDecodingStrategy as .convertFromSnakeCase. No need to muck around with coding keys if you're just converting from snake case. You only need them if you're renaming keys.



          If you have other situations where you need to create custom coding keys for your responses or alter key names, this page should prove helpful.



          You can dump this in a playground and play around with it:



          let jsonResponse = """
          {
          "abilities": [
          {
          "ability": {
          "name": "chlorophyll",
          "url": "https://pokeapi.co/api/v2/ability/34/"
          },
          "is_hidden": true,
          "slot": 3
          },
          {
          "ability": {
          "name": "overgrow",
          "url": "https://pokeapi.co/api/v2/ability/65/"
          },
          "is_hidden": false,
          "slot": 1
          }
          ],
          "name": "SomeRandomName"
          }
          """

          struct Pokemon: Codable {
          let abilities: [AbilityElement]
          let name: String

          struct AbilityElement: Codable {
          let ability: Ability
          let isHidden: Bool
          let slot: Int

          struct Ability: Codable {
          let name: String
          let url: String
          }
          }
          }

          var pokemon: Pokemon?

          do {
          let jsonDecoder = JSONDecoder()
          jsonDecoder.keyDecodingStrategy = .convertFromSnakeCase
          if let data = jsonResponse.data(using: .utf8) {
          pokemon = try jsonDecoder.decode(Pokemon.self, from: data)
          }
          } catch {
          print("Something went horribly wrong:", error.localizedDescription)
          }

          print(pokemon)





          share|improve this answer























          • Thanks Adrian, that site you provided is very helpful. I also knew you could use the coding strategy from snake case to camel case. Just wanted to practice using the coding keys, in case I wanted to switch the names. So to me it looks the same, so I guess I'm stuck doing it like this. But thank you for that helpful site. :)
            – Luis F Ramirez
            Nov 10 at 4:05










          • Coding keys are a PITA, but sometimes you need to use them. If you’re in a production environment or you’ve got proprietary data, would create your structure the “old fashioned” way, not with that site.
            – Adrian
            Nov 10 at 4:08















          up vote
          1
          down vote



          accepted







          up vote
          1
          down vote



          accepted






          Grab your JSON response and dump it in this site.



          It'll generate these structs without Codable. Add Codable so they look like this:



          struct Pokemon: Codable {
          let abilities: [AbilityElement]
          let name: String

          struct AbilityElement: Codable {
          let ability: Ability
          let isHidden: Bool
          let slot: Int

          struct Ability: Codable {
          let name: String
          let url: String
          }
          }
          }


          For keys with snake_case, you can just declare a JSONDecoder and specify the keyDecodingStrategy as .convertFromSnakeCase. No need to muck around with coding keys if you're just converting from snake case. You only need them if you're renaming keys.



          If you have other situations where you need to create custom coding keys for your responses or alter key names, this page should prove helpful.



          You can dump this in a playground and play around with it:



          let jsonResponse = """
          {
          "abilities": [
          {
          "ability": {
          "name": "chlorophyll",
          "url": "https://pokeapi.co/api/v2/ability/34/"
          },
          "is_hidden": true,
          "slot": 3
          },
          {
          "ability": {
          "name": "overgrow",
          "url": "https://pokeapi.co/api/v2/ability/65/"
          },
          "is_hidden": false,
          "slot": 1
          }
          ],
          "name": "SomeRandomName"
          }
          """

          struct Pokemon: Codable {
          let abilities: [AbilityElement]
          let name: String

          struct AbilityElement: Codable {
          let ability: Ability
          let isHidden: Bool
          let slot: Int

          struct Ability: Codable {
          let name: String
          let url: String
          }
          }
          }

          var pokemon: Pokemon?

          do {
          let jsonDecoder = JSONDecoder()
          jsonDecoder.keyDecodingStrategy = .convertFromSnakeCase
          if let data = jsonResponse.data(using: .utf8) {
          pokemon = try jsonDecoder.decode(Pokemon.self, from: data)
          }
          } catch {
          print("Something went horribly wrong:", error.localizedDescription)
          }

          print(pokemon)





          share|improve this answer














          Grab your JSON response and dump it in this site.



          It'll generate these structs without Codable. Add Codable so they look like this:



          struct Pokemon: Codable {
          let abilities: [AbilityElement]
          let name: String

          struct AbilityElement: Codable {
          let ability: Ability
          let isHidden: Bool
          let slot: Int

          struct Ability: Codable {
          let name: String
          let url: String
          }
          }
          }


          For keys with snake_case, you can just declare a JSONDecoder and specify the keyDecodingStrategy as .convertFromSnakeCase. No need to muck around with coding keys if you're just converting from snake case. You only need them if you're renaming keys.



          If you have other situations where you need to create custom coding keys for your responses or alter key names, this page should prove helpful.



          You can dump this in a playground and play around with it:



          let jsonResponse = """
          {
          "abilities": [
          {
          "ability": {
          "name": "chlorophyll",
          "url": "https://pokeapi.co/api/v2/ability/34/"
          },
          "is_hidden": true,
          "slot": 3
          },
          {
          "ability": {
          "name": "overgrow",
          "url": "https://pokeapi.co/api/v2/ability/65/"
          },
          "is_hidden": false,
          "slot": 1
          }
          ],
          "name": "SomeRandomName"
          }
          """

          struct Pokemon: Codable {
          let abilities: [AbilityElement]
          let name: String

          struct AbilityElement: Codable {
          let ability: Ability
          let isHidden: Bool
          let slot: Int

          struct Ability: Codable {
          let name: String
          let url: String
          }
          }
          }

          var pokemon: Pokemon?

          do {
          let jsonDecoder = JSONDecoder()
          jsonDecoder.keyDecodingStrategy = .convertFromSnakeCase
          if let data = jsonResponse.data(using: .utf8) {
          pokemon = try jsonDecoder.decode(Pokemon.self, from: data)
          }
          } catch {
          print("Something went horribly wrong:", error.localizedDescription)
          }

          print(pokemon)






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 10 at 1:23

























          answered Nov 10 at 1:07









          Adrian

          7,919854126




          7,919854126












          • Thanks Adrian, that site you provided is very helpful. I also knew you could use the coding strategy from snake case to camel case. Just wanted to practice using the coding keys, in case I wanted to switch the names. So to me it looks the same, so I guess I'm stuck doing it like this. But thank you for that helpful site. :)
            – Luis F Ramirez
            Nov 10 at 4:05










          • Coding keys are a PITA, but sometimes you need to use them. If you’re in a production environment or you’ve got proprietary data, would create your structure the “old fashioned” way, not with that site.
            – Adrian
            Nov 10 at 4:08




















          • Thanks Adrian, that site you provided is very helpful. I also knew you could use the coding strategy from snake case to camel case. Just wanted to practice using the coding keys, in case I wanted to switch the names. So to me it looks the same, so I guess I'm stuck doing it like this. But thank you for that helpful site. :)
            – Luis F Ramirez
            Nov 10 at 4:05










          • Coding keys are a PITA, but sometimes you need to use them. If you’re in a production environment or you’ve got proprietary data, would create your structure the “old fashioned” way, not with that site.
            – Adrian
            Nov 10 at 4:08


















          Thanks Adrian, that site you provided is very helpful. I also knew you could use the coding strategy from snake case to camel case. Just wanted to practice using the coding keys, in case I wanted to switch the names. So to me it looks the same, so I guess I'm stuck doing it like this. But thank you for that helpful site. :)
          – Luis F Ramirez
          Nov 10 at 4:05




          Thanks Adrian, that site you provided is very helpful. I also knew you could use the coding strategy from snake case to camel case. Just wanted to practice using the coding keys, in case I wanted to switch the names. So to me it looks the same, so I guess I'm stuck doing it like this. But thank you for that helpful site. :)
          – Luis F Ramirez
          Nov 10 at 4:05












          Coding keys are a PITA, but sometimes you need to use them. If you’re in a production environment or you’ve got proprietary data, would create your structure the “old fashioned” way, not with that site.
          – Adrian
          Nov 10 at 4:08






          Coding keys are a PITA, but sometimes you need to use them. If you’re in a production environment or you’ve got proprietary data, would create your structure the “old fashioned” way, not with that site.
          – Adrian
          Nov 10 at 4:08




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53235000%2fparsing-nested-json-using-codable%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Schultheiß

          Verwaltungsgliederung Dänemarks

          Liste der Kulturdenkmale in Wilsdruff