1

I'm having issues creating a struct to parse JSON in Swift 4. I'm able to parse small JSONs and JSONDecoder seems to work fine. Just need help to create a struct to parse JSON like that:

{
    "main": {
        "solutions": [
                    {
                    "exersises": [
                                     {
                                     "book_title": "test",
                                     "release_date": "2015-01-12T11:00",
                                     "price": 100,
                                     "additional": [
                                                   {
                                                   "item1": "test",
                                                   "item2": "test",
                                                   "number": 1
                                                   },
                                                   {
                                                    "item1": "test2",
                                                    "item2": "test2",
                                                    "number": 2
                                                   }
                                                   ],
                                     "availability": "Yes",
                                     "item_id": 43534
                                     }
                                     ]


                    }

                    ]
    }
}

What kind of struct do I need to get to value of book_title for example?

2
  • I am not really sure you should use struct against class but what you need are nested types, e.g. Exercise, Solution etc. Commented Dec 8, 2017 at 19:54
  • I don't understand why this question was downvoted, it's a valid question, I upvote 👍 Commented Mar 28, 2018 at 15:50

2 Answers 2

3

Its really easy. Your main probem is most likely root element. Let me get first layer or two for you.

let decoded = try JSONDecoder().decode(MainJSON.self, from: data)

class MainJSON: Codable {
    var main:SolutionJSON?
}

class SolutionJSON: Codable {
    var exercises:[ExercisesJSON]?
}

class ExercisesJSON: Codable {
    var bookTitle: String?
    var releaseDate: String?
    var price: Double?
    ... etc

    enum CodingKeys: String, CodingKey {
        case bookTitle = "book_title"
        case releaseDate = "release_date"
        case price = "price"
    }
}

ExerciseJSON also uses Codable interface which lets remap json properties into swift properties if they don't match. Hope this helps.

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks a lot that's exactly what I was looking for, I couldn't figure out the logic for root elements. I had to add one more level actually to be able to display elements. Do you know how to access the book_title ? I'm trying decoded.main.solutions.exersises[0].book_title. and getting an error
Nevermind, I got it figured out: print(decoded.main!.solutions![0].exersises![0].bookTitle!)
@MikeT I would use structures instead of classes and declare all properties non optional and constants
Btw releaseDate should be declared as date and set the decoder dateDecodingStrategy to .formatted and provide a fixed-format dateFormatter to parse that string "yyyy-MM-dd'T'HH:mm" stackoverflow.com/a/47705410/2303865
MainJSON and SolutionJSON should conform to Codable protocol. Donna know why the code in the answer builds
|
-2

i prefer to give a general solution not only for this condition

it is very simple just download and run this MACOS APP from GITHUB run it in your mac by XCODE and but your JSON in it,
it will make Models for any complex JSON

notes

1 if JSON keys have a capital character in the first it will be small , so after copying model you need to change it like the JSON

2 if two JSON objects have the same structure and the same key names it will be only one model

3 Comments

I tried to use the app but the result is really strange, for the particular JSON mentioned above in my question I get 3 different files... Is it possible to get it in the swift struct format as mentioned in the previous answer ?
you can but them in one file it isn't difficult , or you can but classes or structs in each other if you want your code to be clean
yes you can get it in swift struct ,java class ,or objective c ,if you look on the right bottom corner in question image

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.