将数组序列化为 swift 中的对象

serializing array to object in swift

我有以下对象 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]) {

guard

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! {

    self.referencesArray.append(object)
    //print(object)
}

//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)
        newsItems.append(newsArticle!)

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

}

在应用程序的后端,我有 JSON 个对象,每个对象的值之一如下:

... "reference" : [
        {
            "refName": "CNN",
            "refURL": "http://edition.cnn.com/2016/07/19/football/brexit-effect-on-english-premier-league/index.html"
        },
        {
            "refName": "Telegraph",  
            "refURL": "http://www.telegraph.co.uk/football/2016/06/21/what-would-brexit-mean-for-the-premier-league/"
        }

    ], ...

我不知道我是否有 JSON 错误的东西,但我想要的是一个引用数组,每个引用都有一个引用名称(refName)和 url 的参考 (refURL)。

我的问题是,将上面的 JSON 对象添加到我的对象 class 中的 referencesArray 的最佳方法是什么。使用字典而不是数组会更好吗?如果是这样,我应该如何重写我的代码?

如果您需要有关代码的更多详细信息,请询问,您会收到更新。谢谢!

编辑

这是 JSON 的完整内容:

{

"stories" : [

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

    "headerImage" : "http://i2.cdn.turner.com/cnnnext/dam/assets/160117112140-rooney-goal-exlarge-169.jpg",

    "category" : "Sports",

    "paragraph1" : "Paragraph text", 

    "paragraph2" : "More text goes here",

    "date" : "21st July",

    "majorReference" : "CNN",

    "reference" : [
        {
            "refName": "CNN",
            "refURL": "http://edition.cnn.com/2016/07/19/football/brexit-effect-on-english-premier-league/index.html"
        },
        {
            "refName": "Telegraph",  
            "refURL": "http://www.telegraph.co.uk/football/2016/06/21/what-would-brexit-mean-for-the-premier-league/"
        }

    ],

    "secondImage"   :   "http://www.telegraph.co.uk/content/dam/football/2016/06/14/02-leicester-afp-xlarge_trans++Wy_u4a9GUNQgLIY2EGV3qvLCN329DeTLuwi-bwi35Bo.jpg",

    "fact" : "Talent will go missing"

    },  ...

那只是一个故事...逗号之后是另一个故事。

首先定义一个数据模型供大家参考:

struct NewsItemReference {
    var refName: String
    var refURL: NSURL
}

然后修改你的NewsItemclass如下:

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 {
                    continue
                }

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

如果您发现自己很快就超出了这个模型(代码太冗长),请查看一些 JSON 到对象的映射框架,例如 ObjectMapper