jjzjj

ios - 带模型的 SwiftyJson 嵌套数组

coder 2023-09-13 原文

如何使用 SwiftyJSON 和第二组嵌套对象数组创建数据模型?我能够很好地解析和存储顶级对象,但不能解析和存储内部对象。特别是noteimages,我似乎无法弄清楚。下面是 api 结果,下面是我尝试这样做的方式,尽管不太正确。

[
{
    "id": 1,
    "title": "some title",
    "details": "here are some details",
    "userId": 1,
    "hidden": false,
    "createdAt": "2018-02-14T07:02:33.000Z",
    "updatedAt": "2018-02-14T07:02:33.000Z",
    "contactId": 1,
    "noteimages": [
        {
            "id": 2,
            "imageUrl": "someimage222.jpg",
            "userId": 1,
            "hidden": false,
            "createdAt": "2018-02-14T07:02:58.000Z",
            "updatedAt": "2018-02-15T04:41:05.000Z",
            "noteId": 1
        }
    ]
}
]

Alamofire.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: header).responseJSON { (response) in

        if response.result.error == nil {
            guard let data = response.data else { return }
            do {
                if let json = try JSON(data: data).array {
                    print(json)
                    for item in json {
                        let title = item["title"].stringValue
                        let details = item["details"].stringValue

                        var noteImages: [Dictionary<String, AnyObject>]
                        for image in item["noteimages"].arrayValue {
                            noteImages.append(image["imageUrl"])
                        }

                        let note = Note(title: title, details: details, noteImage: noteImages)
                        self.notes.append(note)
                    }
                    //print(response)
                    completion(true)
                }
            } catch {
                debugPrint(error)
            }

        } else {
            completion(false)
            debugPrint(response.result.error as Any)
        }

    }

最佳答案

您的问题是您正在获取键 imageUrl 中的值字符串,并且您正在添加为字典,因此如果您需要一个字典数组,您需要将这些值添加到 item["noteimages"].arrayValue 直接或者如果您需要 imageUrl 数组,您需要将 noteImages var 的类型更改为 String类型

var noteImages: [Dictionary<String, AnyObject>]// this should be [String:AnyObject]] swifty way
for image in item["noteimages"].arrayValue {
    noteImages.append(image["imageUrl"]) //this is an String not an Dictionary
}

要解决此问题,您需要三个选项之一

方案一:使用字典数组

var noteImages: [[String:AnyObject]] = []
for image in item["noteimages"].arrayValue {
   if let imageDict = image as? [String:AnyObject]{
       noteImages.append(imageDict) //adding in a dictionary array
    }
}

选项 2:使用字符串数组

var noteImages: [String] = []
for image in item["noteimages"].arrayValue {
   if let imageDict = image as? [String:AnyObject]{
       noteImages.append(imageDict["imageUrl"])
    }
}

选项 3:将您的字典转换为模型对象

var noteImages: [YourModelName] = []
for image in item["noteimages"].arrayValue {
   if let imageDict = image as? [String:AnyObject]{
       noteImages.append(YourModelName(dictionary:imageDict)) //adding in a model object created from a dictionary
    }
}

关于ios - 带模型的 SwiftyJson 嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48849061/

有关ios - 带模型的 SwiftyJson 嵌套数组的更多相关文章

  1. ruby-on-rails - Rails - 子类化模型的设计模式是什么? - 2

    我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co

  2. ruby-on-rails - Rails 编辑表单不显示嵌套项 - 2

    我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib

  3. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

    我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

  4. ruby - 多次弹出/移动 ruby​​ 数组 - 2

    我的代码目前看起来像这样numbers=[1,2,3,4,5]defpop_threepop=[]3.times{pop有没有办法在一行中完成pop_three方法中的内容?我基本上想做类似numbers.slice(0,3)的事情,但要删除切片中的数组项。嗯...嗯,我想我刚刚意识到我可以试试slice! 最佳答案 是numbers.pop(3)或者numbers.shift(3)如果你想要另一边。 关于ruby-多次弹出/移动ruby​​数组,我们在StackOverflow上找到一

  5. ruby - 将数组的内容转换为 int - 2

    我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]

  6. ruby-on-rails - Rails - 一个 View 中的多个模型 - 2

    我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何

  7. ruby - 将散列转换为嵌套散列 - 2

    这道题是thisquestion的逆题.给定一个散列,每个键都有一个数组,例如{[:a,:b,:c]=>1,[:a,:b,:d]=>2,[:a,:e]=>3,[:f]=>4,}将其转换为嵌套哈希的最佳方法是什么{:a=>{:b=>{:c=>1,:d=>2},:e=>3,},:f=>4,} 最佳答案 这是一个迭代的解决方案,递归的解决方案留给读者作为练习:defconvert(h={})ret={}h.eachdo|k,v|node=retk[0..-2].each{|x|node[x]||={};node=node[x]}node[

  8. ruby-on-rails - 在混合/模块中覆盖模型的属性访问器 - 2

    我有一个包含模块的模型。我想在模块中覆盖模型的访问器方法。例如:classBlah这显然行不通。有什么想法可以实现吗? 最佳答案 您的代码看起来是正确的。我们正在毫无困难地使用这个确切的模式。如果我没记错的话,Rails使用#method_missing作为属性setter,因此您的模块将优先,阻止ActiveRecord的setter。如果您正在使用ActiveSupport::Concern(参见thisblogpost),那么您的实例方法需要进入一个特殊的模块:classBlah

  9. ruby - 通过 erb 模板输出 ruby​​ 数组 - 2

    我正在使用puppet为ruby​​程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby​​不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这

  10. ruby-on-rails - 如何验证非模型(甚至非对象)字段 - 2

    我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss

随机推荐