来自对象的 JSON 在 iOS Swift 3 中出现数组问题

Posted

技术标签:

【中文标题】来自对象的 JSON 在 iOS Swift 3 中出现数组问题【英文标题】:JSON from Object with array issue in iOS Swift 3 【发布时间】:2017-04-22 06:56:06 【问题描述】:
public class LessonAssignment 

    private var title : String?
    private var category : String?
    private var week : Int?
    private var day : Int?


    //Title
    public func getTitle() -> String 
        return title!
    

    public func setTitle(title : String) 
        self.title = title
    

    //Category
    public func getCategory() -> String 
        return category!
    

    public func setCategory(category : String) 
        self.category = category
    

    //Week
    public func getWeek() -> Int 
        return week!
    

    public func setWeek(week : Int) 
        self.week = week
    

    //Day
    public func getDay() -> Int 
        return day!
    

    public func setDay(day : Int) 
        self.day = day
    

/**
    Returns an array of models based on given dictionary.

    Sample usage:
    let lessonAssignment_list = LessonAssignment.modelsFromDictionaryArray(someDictionaryArrayFromJSON)

    - parameter array:  NSArray from JSON dictionary.

    - returns: Array of LessonAssignment Instances.
*/
    public class func modelsFromDictionaryArray(array:NSArray) -> [LessonAssignment]
    
        var models = [LessonAssignment]()
        for item in array 
            models.append(LessonAssignment(dictionary: item as! NSDictionary)!)
        
        return models
    

/**
    Constructs the object based on the given dictionary.

    Sample usage:
    let lessonAssignment = LessonAssignment(someDictionaryFromJSON)

    - parameter dictionary:  NSDictionary from JSON.

    - returns: LessonAssignment Instance.
*/
     init()  

    required public init?(dictionary: NSDictionary) 

        title = dictionary["title"] as? String
        category = dictionary["category"] as? String
        week = dictionary["week"] as? Int
        day = dictionary["day"] as? Int
    


/**
    Returns the dictionary representation for the current instance.

    - returns: NSDictionary.
*/
    public func dictionaryRepresentation() -> NSDictionary 

        let dictionary = NSMutableDictionary()

        dictionary.setValue(self.title, forKey: "title")
        dictionary.setValue(self.category, forKey: "category")
        dictionary.setValue(self.week, forKey: "week")
        dictionary.setValue(self.day, forKey: "day")

        return dictionary
    

    func toDictionary() -> [String : Any] 
        var dictionary = [String:Any]()
        let otherSelf = Mirror(reflecting: self)

        for child in otherSelf.children 
            if let key = child.label 
                dictionary[key] = child.value
            
        
        return dictionary
    




public class LessonPlan 
    private var name : String?
    private var weeks : Int?
    private var days : Int?
    private var hours : Int?
    private var lessonAssignment = [LessonAssignment]()
    private var lessonNote = [LessonNote]()


    //Name
    public func getName() -> String 
        if name == nil 
            return ""
         else 
            return name!
        
    

    public func setName(name : String) 
        self.name = name
    

    //Weeks
    public func getWeeks() -> Int 
        if weeks == 0 
            return 0
         else 
            return weeks!
        
    

    public func setWeeks(weeks : Int) 
        self.weeks = weeks
    

    //Days
    public func getDays() -> Int 
        if days == 0 
            return 0
         else 
            return days!
        
    

    public func setDays(days : Int) 
        self.days = days
    

    //Hours
    public func getHours() -> Int 
        if days == 0 
            return 0
         else 
            return hours!
        
    

    public func setHours(hours : Int) 
        self.hours = hours
    

    //LessonAssignment
    public func getLessonAssignment() -> [LessonAssignment] 
        return lessonAssignment
    

    public func setLessonAssignment(lessonAssignment : [LessonAssignment]) 
        self.lessonAssignment = lessonAssignment
    

    //LessonNote
    public func getLessonNote() -> [LessonNote] 
        return lessonNote
    

    public func setLessonNote(lessonNote : [LessonNote]) 
        self.lessonNote = lessonNote
    


/**
    Returns an array of models based on given dictionary.

    Sample usage:
    let lessonPlan_list = LessonPlan.modelsFromDictionaryArray(someDictionaryArrayFromJSON)

    - parameter array:  NSArray from JSON dictionary.

    - returns: Array of LessonPlan Instances.
*/
    public class func modelsFromDictionaryArray(array:NSArray) -> [LessonPlan]
    
        var models:[LessonPlan] = []
        for item in array
        
            models.append(LessonPlan(dictionary: item as! NSDictionary)!)
        
        return models
    

/**
    Constructs the object based on the given dictionary.

    Sample usage:
    let lessonPlan = LessonPlan(someDictionaryFromJSON)

    - parameter dictionary:  NSDictionary from JSON.

    - returns: LessonPlan Instance.
*/
     init()  

    required public init?(dictionary: NSDictionary) 

        name = dictionary["name"] as? String
        weeks = dictionary["weeks"] as? Int
        days = dictionary["days"] as? Int
        hours = dictionary["hours"] as? Int

        lessonAssignment = LessonAssignment.modelsFromDictionaryArray(array:dictionary["lessonAssignment"] as! NSArray)

        lessonNote = LessonNote.modelsFromDictionaryArray(array: dictionary["lessonNote"] as! NSArray)
    


/**
    Returns the dictionary representation for the current instance.

    - returns: NSDictionary.
*/
    public func dictionaryRepresentation() -> NSDictionary 
        let dictionary = NSMutableDictionary()
        dictionary.setValue(self.name, forKey: "name")
        dictionary.setValue(self.weeks, forKey: "weeks")
        dictionary.setValue(self.days, forKey: "days")
        dictionary.setValue(self.hours, forKey: "hours")
        return dictionary
    

    func toDictionary() -> [String : Any] 
        var dictionary = [String:Any]()
        let otherSelf = Mirror(reflecting: self)

        for child in otherSelf.children 
            print("Child = \(child)")
            print("Child Label = \(String(describing: child.label))")
            print("Child Value = \(child.value)")

            if let key = child.label 
                 dictionary[key] = child.value
            
        
        return dictionary
    

公共类 ServerRequest

private var lessonPlan : LessonPlan?

init() 


//LessonPlan
public func getLessonPlan() -> LessonPlan 
    return lessonPlan!


public func setLessonPlan(lessonPlan : LessonPlan) 
    self.lessonPlan = lessonPlan


func toDictionary() -> [String : Any] 
    var dictionary = [String:Any]()
    let otherSelf = Mirror(reflecting: self)

    for child in otherSelf.children 
        if let key = child.label 
            dictionary[key] = lessonPlan?.toDictionary()
        
    
    return dictionary

当前响应 = ["lessonPlan": ["name": "test", "days": 2, "weeks": 1, "小时": 1, "lessonAssignment": [HSP.LessonAssignment, HSP.LessonAssignment], "lessonNote": []]]

预期反应 = ["lessonPlan": ["name": "test", "days": 2, "weeks": 1, "hours": 1, "lessonAssignment": [["title" : "some value 1", "category" : "some value", "week" : 1, "day" : 2]] , "教训笔记": []]]

我想添加的是数组的实际值,而不是 LessinAssignment 对象。任何线索如何解决这个问题。我知道我必须在 toDictionary 方法中添加更多逻辑,并且基于键“lessonAssignment”我必须获取每个数组并将键中的值添加为最终数组。

【问题讨论】:

不相关,但 LessonPlan 类中的所有自定义 getter 和 setter 都是无意义的。这是斯威夫特!为什么所有属性都是可选的,尽管 setter 传递了非可选值? lessonAssignment 键是一个 LessonAssignment 实例数组? @vadian 是的,我们知道它很快,但我们遵循 getter/setter 作为我们的标准做法。 @chri 是的,课程分配是自定义类的数组。 并且您想要该实例的每个数组条目的属性作为课程分配键而不是整个实例? 【参考方案1】:

从我的评论来看,是这样的:

assignments.map(
  (value: HSP.LessonAssignment) -> NSDictionary in
  return value.toDictionary()
)

【讨论】:

以上是关于来自对象的 JSON 在 iOS Swift 3 中出现数组问题的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Swift 3 中解析来自 URL 的 JSON 数据

使用 Swift 3 和 iOS 在发送到 Parse Server 的 authdata 对象中使用来自 google 登录的哪个 authdata

如何在 ios swift 中创建 json 对象

iOS Swift 解析来自 Alamofire 的 JSON 响应

在 Swift 3 中解析 JSON,就像 Apple 的 Swift 2 示例一样

如何在 Swift 3 中为来自 web 服务的 Json 响应创建模型类