Mwi Ti Mwi Ti - 2 months ago 4
JSON Question

serializing array to object in swift

i have the following object class:

class NewsItem: NSObject {

var storyCategory: String?
var titleText: String?
var paragraph1: String?
var paragraph2: String?
var featureImage: String?
var secondImage: String?
var storyDate: String?
var majorReference: String?
var fact: String?
var actualFeatureImage: UIImage? // Using these two to pass the image from home to story view
var actualSecondImage: UIImage?

var referencesArray = [AnyObject]()

init?(dictionary: [String: AnyObject]) {


let storyCategory = dictionary["category"] as? String,
let titleText = dictionary["title"] as? String,
let paragraph1 = dictionary["paragraph1"] as? String,
let paragraph2 = dictionary["paragraph2"] as? String,
let featureImage = dictionary["headerImage"] as? String,
let storyDate = dictionary["date"] as? String,
let majorReference = dictionary["majorReference"] as? String,
let secondImage = dictionary["secondImage"] as? String

else {
return nil

self.storyCategory = storyCategory
self.titleText = titleText
self.paragraph2 = paragraph2
self.paragraph1 = paragraph1
self.featureImage = featureImage
self.storyDate = storyDate
self.majorReference = majorReference
self.fact = dictionary["fact"] as? String //if there's a fact in the dict, it will be assigned and if not there'll be nil
self.secondImage = secondImage

let referenceObject = dictionary["reference"] as? [[String: AnyObject]]
for object in referenceObject! {


//bellow is a snippet from the method that's serializing the JSON data

do {
let json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)

if let newsArticles = json["stories"] as? [[String: AnyObject]] {
for article in newsArticles {
let newsArticle = NewsItem(dictionary: article)

} catch {
print("error in the news items delivery: \(error)")
let displayError = EHPlainAlert(title: "hmmm...", message: "\(error)", type: ViewAlertError)


in the backend of the app, i have JSON objects and one of the values of each of the objects is as follows:

... "reference" : [
"refName": "CNN",
"refURL": ""
"refName": "Telegraph",
"refURL": ""

], ...

i don't know if i have the JSON wrong o' something but what i intend to have is an array of references, each reference having a reference name(refName) and the url of the reference (refURL).

my question is, what would be the best method to have the JSON object above be added to the referencesArray in my object class. Would it be better to use a dictionary instead of an array? if so, how should i re-write my code?

if you need any more details about the code, ask and ye shall receive an update. Thanks!


Here's the JSON in full :


"stories" : [

"title" : "English Premier League vs BREXIT: Who will win?",

"headerImage" : "",

"category" : "Sports",

"paragraph1" : "Paragraph text",

"paragraph2" : "More text goes here",

"date" : "21st July",

"majorReference" : "CNN",

"reference" : [
"refName": "CNN",
"refURL": ""
"refName": "Telegraph",
"refURL": ""


"secondImage" : "",

"fact" : "Talent will go missing"

}, ...

Thats just one story... after the comma, is another story.


First, define a data model for your reference:

struct NewsItemReference {
    var refName: String
    var refURL: NSURL

Then modify your NewsItem class as below:

class NewsItem: NSObject {
    var referencesArray = [NewsItemReference]()

    init?(dictionary: [String: AnyObject]) {
        if let references = dictionary["reference"] as? [[String: AnyObject]] {
            for object in references {
                guard let refName = object["refName"] as? String,
                      let refURLString = object["refURL"] as? String,
                      let refURL = NSURL(string: refURLString) else {

                self.referencesArray.append(NewsItemReference(refName: refName, refURL: refURL))

If you see yourself quickly outgrowing this model (the code is too verbose), take a look at some JSON-to-object mapping framework like ObjectMapper.