0

I am writing an IOS Application that need to read a JSON FIle. I understood the best way to do that is to write a struct for that json file and parse the json into that struct to be able to use freely.

I have a Json file that is saved locally in one of the folders

{
  "colors": [
    {
      "color": "black",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [255,255,255,1],
        "hex": "#000"
      }
    },
    {
      "color": "white",
      "category": "value",
      "code": {
        "rgba": [0,0,0,1],
        "hex": "#FFF"
      }
    },
    {
      "color": "red",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [255,0,0,1],
        "hex": "#FF0"
      }
    },
    {
      "color": "blue",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [0,0,255,1],
        "hex": "#00F"
      }
    },
    {
      "color": "yellow",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [255,255,0,1],
        "hex": "#FF0"
      }
    },
    {
      "color": "green",
      "category": "hue",
      "type": "secondary",
      "code": {
        "rgba": [0,255,0,1],
        "hex": "#0F0"
      }
    },
  ],

  "people": [
    {
      "first_name": "john",
      "is_valid": true,
      "friends_list": {
        "friend_names": ["black", "hub", "good"],
        "age": 13
      }
    },
    {
      "first_name": "michal",
      "is_valid": true,
      "friends_list": {
        "friend_names": ["jessy", "lyn", "good"],
        "age": 19
      }
    },
    {
      "first_name": "sandy",
      "is_valid": false,
      "friends_list": {
        "friend_names": ["brown", "hub", "good"],
        "age": 15
      }
    },
  ]
}

i created a struct for each one of the two tables:

import Foundation

struct Color {
    var color: String
    var category: String
    var type: String
    var code: [JsonCodeStruct]
}

struct Poeople {
    var firsName: String
    var is_valid: Bool
    var friendsNames: [JsonFriendNames]

}

struct JsonFriendNames {
    var friendNames: [String]
    var age: String
}

struct JsonCodeStruct {
    var rgba: [Double]
    var hex: String

}

and I want to open the local json file and assign it the structs that I gave and then read them easily in the code.

can you suggest me a way on how to do that?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Chief Madog
  • 1,738
  • 4
  • 28
  • 55

1 Answers1

4

First of all you need an umbrella struct to decode the colors and people keys

struct Root: Decodable {
    let colors: [Color]
    let people : [Person]
}

The types in your structs are partially wrong. The Color related structs are

struct Color: Decodable {
    let color: String
    let category: String
    let type: String?
    let code : ColorCode
}

struct ColorCode: Decodable {
    let rgba : [UInt8]
    let hex : String
}

and the Person related structs are

struct Person: Decodable {
    let firstName : String
    let isValid : Bool
    let friendsList : Friends
}

struct Friends: Decodable {
    let friendNames : [String]
    let age : Int
}

Assuming you read the file with

let data = try Data(contentsOf: URL(fileURLWithPath:"/...."))

you can decode the JSON into the given structs with

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
do {
    let result = try decoder.decode(Root.self, from: data)
    print(result)
} catch { print(error) }
vadian
  • 274,689
  • 30
  • 353
  • 361
  • it comes up as error, for the data line. - The JSON file is in a folder called "Resurces" - ive added let data = try Data(contentsOf: URL(fileURLWithPath:"/Recourses/colors.json")) but it doesn't compile – Chief Madog Oct 23 '18 at 11:40
  • `Resurces` where? You have to specify the real full path to the file. If the file is in the bundle the URL is `Bundle.main.url(forResource: "colors", withExtension: "json")`. – vadian Oct 23 '18 at 11:43
  • Worked for me gave u the best answer, what does it mean that we created a Root: Decodable, does it mean i cannot use the decodable or the structs for other stuff in my app ? – Chief Madog Oct 23 '18 at 11:53
  • You have to decode JSON always from the top level object which is represented by the `Root` struct (the name is arbitrary) and all structs must match the corresponding JSON data. – vadian Oct 23 '18 at 12:00
  • Thank you , and if i want to return the result in a function, what type would the function return ? – Chief Madog Oct 23 '18 at 12:03
  • In this case also `Root`. You can get the colors with the `colors` property and the people with `people`. – vadian Oct 23 '18 at 12:04