Group Group Group Group Group Group Group Group Group

Having problems with Codable

#1

My Xcode Program

This is my very first Codable program and I am totally lost in why I can nota even able to get it to read the JSON. Can someone please give me some guidance in what I am doing wrong.

Now, on a different note, I have this working with SwiftyJSON, I just want to learn Codable and get away from a third party file.
Thank you ahead of time for all replies .
Robert

#2

The Ray Wenderlich site has a handy tutorial on Encoding, Decoding and Serialization in Swift 4, you can find it here: https://www.raywenderlich.com/382-encoding-decoding-and-serialization-in-swift-4 .

#3

Thank. you, but no matter how often I went through it. I am not getting what I am doing wrong. All the examples are for simple a JSON. Can someone just look at my code and tell me what I am doing wrong. I have been looking at it for over 3 days and it is not sticking out on what I am doing wrong. This is an example that your reply to me is SO WRONG and you paid very little attention to my problem. The mistake that I made had to to do with on how I interacted with my Object. And what you pointed me to, did not address the problem that I had encountered. I WAS GOING CRAZY AND SPENT ALMOST 4 DAYS on this. I have read allot of tutorials and no one covered oh how you address Objects in JSON.

They all provided Simple examples like this.
struct GroceryProduct: Codable {
var name: String
var points: Int
var description: String?
}

let json = “”"
{
“name”: “Durian”,
“points”: 600,
“description”: “A fruit with a distinctive scent.”
}

I will be leaving my Program up for others to learn from.
All I did was changed
struct Petitions: Codable {
var results: [Petition]
}
to
struct Petitions: Codable {
var Story: [Petition]
}

#4

hi @hcri1950,
Rob, your problem is based from the code sample, a very specific issue as compared to a generic issue with codable.

In your code you have Story as a structure and in the code above you are trying to create a variable Story that holds an array of Petitions, that is an error

secondly, if you share the error and screenshots, it would help others help you better, not everyone would download a project to look into.

Hope that resolves your problem,

cheers,

#5

Hi @hcri1950,

Unsure if you looked at the link @gdelarosa sent. One thing to keep in mind is that the name is critical, e.g. use the following if there are key-name differences

enum CodingKeys : String, CodingKey {...}. 

I looked at your code and the JSON

There is no key named results. If you change the variable name to the following it should work.

var Story: [Story]

Hope you get the hang of it.

-JT

#6

Thank you, very much. and sorry for not replying earlier. But for some reason, I am not getting alerted of all replies. I need to check to see why I am not getting alerted. I did resolve my problem. THANK YOU.

#7

Hi @hcri1950,
glad it worked for you.

cheers,