【问题标题】:How to handle object mapping with dynamic keys in swift 5如何在 swift 5 中使用动态键处理对象映射
【发布时间】:2019-11-08 13:07:50
【问题描述】:

我正在尝试使模型类使用动态键及其值来处理 JSON 响应,但出现错误,即

调用中的参数标签不正确(有 'JSON:',预期为 'map:') 将“JSON”替换为“map”,同时将数据解析到模型类。

我正在使用 ObjectMapper 进行映射 JSON 响应

低于我到现在为止的尝试:

处理 JSON 响应对象的热门课程响应模型

import Foundation    
import ObjectMapper

struct StudentTopCouses: Mappable {        
    init?(map: Map) {}

    var results: [String: [CoursesListObject]]?

    mutating func mapping(map: Map) {
        results   <- map["data"]
    }
}

class CoursesListObject: Mappable {

    var id: NSNumber?
    var createdOn: NSNumber?
    var name: String?
    var description: String?
    var createdBy: String?
    var approved: Bool?
    var reason: String?
    var courseStatus: String?
    var courseCategory: CourseCategory?

    required init?(map: Map) {}

    func mapping(map: Map) {
        id <- map["id"]
        createdOn <- map["createdOn"]
        name <- map["name"]
        description <- map["description"]
        createdBy <- map["createdBy"]
        approved <- map["approved"]
        reason <- map["reason"]
        courseStatus <- map["courseStatus"]
        courseCategory <- map["courseCategory"]
    }
}


class CourseCategory: Mappable {

var id: NSNumber?
var createdOn: NSNumber?
var category: String?
var description: Any?

required init?(map: Map){
}

func mapping(map: Map) {
    id <- map["id"]
    createdOn <- map["createdOn"]
    category <- map["category"]
    description <- map["description"]
  }
}

Top Courses API 成功函数:

 func getTopCourseNetworkCallSuccess(data : JSON){

    if data["isSuccess"].boolValue {

        ActivityIndicator.shared.hideProgressView()

        if let r = StudentTopCouses.init(JSON: data), let result = r.results {
            for (key, value) in result {
                print("Key: \(key)" )
                print("Course Name: \(value.first!.name!)")
            }
        }   
    } else {
        //Handle Error Response
    }
}

这是我这样的 API JSON 响应

{
    "data": {
        "ManualTesting": [
            {
                "id": 1949,
                "createdOn": 1572433478000,
                "name": "Software Testing",
                "description": "It's a type of software Testing",
                "createdBy": "opp",
                "approved": true,
                "reason": "asdasdasdcassdqadaxasdasd",
                "courseStatus": "APPROVED",
                "courseCategory": {
                    "id": 1916,
                    "createdOn": 1572421487000,
                    "category": "ManualTesting",
                    "description": "Ultimate QA Manual Testing course with Live project and Live demo + Real time interview questions + Life time support"
                }
            }
        ],
        "Java Technology": [
            {
                "id": 2064,
                "createdOn": 1572609103000,
                "name": "hfjfjf",
                "description": "hchcjcf\n",
                "createdBy": "Tq",
                "approved": true,
                "reason": null,
                "courseStatus": "APPROVED",
                "courseCategory": {
                    "id": 1910,
                    "createdOn": 1572346886000,
                    "category": "Java Technology",
                    "description": "Learn Java In This Course And Become a Computer Programmer. Obtain valuable Core Java Skills And Java Certification"
                }
            },
            {
                "id": 2159,
                "createdOn": 1572868301000,
                "name": "Spring beginner",
                "description": "we will teach you a spring boot.",
                "createdBy": "Haris",
                "approved": true,
                "reason": null,
                "courseStatus": "APPROVED",
                "courseCategory": {
                    "id": 1910,
                    "createdOn": 1572346886000,
                    "category": "Java Technology",
                    "description": "Learn Java In This Course And Become a Computer Programmer. Obtain valuable Core Java Skills And Java Certification"
                }
            },
            {
                "id": 2168,
                "createdOn": 1572871357000,
                "name": "Multi Threading",
                "description": "we will teach you multi threading",
                "createdBy": "Haris",
                "approved": true,
                "reason": null,
                "courseStatus": "APPROVED",
                "courseCategory": {
                    "id": 1910,
                    "createdOn": 1572346886000,
                    "category": "Java Technology",
                    "description": "Learn Java In This Course And Become a Computer Programmer. Obtain valuable Core Java Skills And Java Certification"
                }
            },
            {
                "id": 2169,
                "createdOn": 1572871521000,
                "name": "Hybernate ",
                "description": "we will teach you hybernate",
                "createdBy": "Haris",
                "approved": true,
                "reason": null,
                "courseStatus": "APPROVED",
                "courseCategory": {
                    "id": 1910,
                    "createdOn": 1572346886000,
                    "category": "Java Technology",
                    "description": "Learn Java In This Course And Become a Computer Programmer. Obtain valuable Core Java Skills And Java Certification"
                }
            },
            {
                "id": 2293,
                "createdOn": 1573032019000,
                "name": "Spring",
                "description": "we will teach you spring",
                "createdBy": "hard",
                "approved": true,
                "reason": "",
                "courseStatus": "APPROVED",
                "courseCategory": {
                    "id": 1910,
                    "createdOn": 1572346886000,
                    "category": "Java Technology",
                    "description": "Learn Java In This Course And Become a Computer Programmer. Obtain valuable Core Java Skills And Java Certification"
                }
            }
        ],
        "Python Technology": [
            {
                "id": 2041,
                "createdOn": 1572601461000,
                "name": "Python for Data Science and Machine Learning Bootcamp",
                "description": "Learn how to use NumPy, Pandas, Seaborn , Matplotlib , Plotly , Scikit-Learn , Machine Learning, Tensorflow , and more",
                "createdBy": "DL",
                "approved": true,
                "reason": null,
                "courseStatus": "APPROVED",
                "courseCategory": {
                    "id": 1912,
                    "createdOn": 1572346929000,
                    "category": "Python Technology",
                    "description": "This Python For Beginners Course Teaches You The Python Language Fast. Includes Python Online Training With Python 3"
                }
            },
            {
                "id": 2043,
                "createdOn": 1572604907000,
                "name": "Learn Python Programming Masterclass",
                "description": "This Python For Beginners Course Teaches You The Python Language Fast. Includes Python Online Training With Python 3",
                "createdBy": "DL",
                "approved": true,
                "reason": null,
                "courseStatus": "APPROVED",
                "courseCategory": {
                    "id": 1912,
                    "createdOn": 1572346929000,
                    "category": "Python Technology",
                    "description": "This Python For Beginners Course Teaches You The Python Language Fast. Includes Python Online Training With Python 3"
                }
            },
            {
                "id": 2044,
                "createdOn": 1572604961000,
                "name": "The Python Bible™ | Everything You Need to Program in Python",
                "description": "Build 11 Projects and go from Beginner to Pro in Python with the World's Most Fun Project-Based Python Course!",
                "createdBy": "DL",
                "approved": true,
                "reason": null,
                "courseStatus": "APPROVED",
                "courseCategory": {
                    "id": 1912,
                    "createdOn": 1572346929000,
                    "category": "Python Technology",
                    "description": "This Python For Beginners Course Teaches You The Python Language Fast. Includes Python Online Training With Python 3"
                }
            },
            {
                "id": 2046,
                "createdOn": 1572604968000,
                "name": "The Python Bible™ | Everything You Need to Program in Python",
                "description": "Build 11 Projects and go from Beginner to Pro in Python with the World's Most Fun Project-Based Python Course!",
                "createdBy": "DL",
                "approved": true,
                "reason": null,
                "courseStatus": "APPROVED",
                "courseCategory": {
                    "id": 1912,
                    "createdOn": 1572346929000,
                    "category": "Python Technology",
                    "description": "This Python For Beginners Course Teaches You The Python Language Fast. Includes Python Online Training With Python 3"
                }
            },
            {
                "id": 2047,
                "createdOn": 1572604969000,
                "name": "The Python Bible™ | Everything You Need to Program in Python",
                "description": "Build 11 Projects and go from Beginner to Pro in Python with the World's Most Fun Project-Based Python Course!",
                "createdBy": "DL",
                "approved": true,
                "reason": null,
                "courseStatus": "APPROVED",
                "courseCategory": {
                    "id": 1912,
                    "createdOn": 1572346929000,
                    "category": "Python Technology",
                    "description": "This Python For Beginners Course Teaches You The Python Language Fast. Includes Python Online Training With Python 3"
                }
            },
            {
                "id": 2048,
                "createdOn": 1572604971000,
                "name": "The Python Bible™ | Everything You Need to Program in Python",
                "description": "Build 11 Projects and go from Beginner to Pro in Python with the World's Most Fun Project-Based Python Course!",
                "createdBy": "DL",
                "approved": true,
                "reason": null,
                "courseStatus": "APPROVED",
                "courseCategory": {
                    "id": 1912,
                    "createdOn": 1572346929000,
                    "category": "Python Technology",
                    "description": "This Python For Beginners Course Teaches You The Python Language Fast. Includes Python Online Training With Python 3"
                }
            },
            {
                "id": 2049,
                "createdOn": 1572604972000,
                "name": "The Python Bible™ | Everything You Need to Program in Python",
                "description": "Build 11 Projects and go from Beginner to Pro in Python with the World's Most Fun Project-Based Python Course!",
                "createdBy": "DL",
                "approved": true,
                "reason": null,
                "courseStatus": "APPROVED",
                "courseCategory": {
                    "id": 1912,
                    "createdOn": 1572346929000,
                    "category": "Python Technology",
                    "description": "This Python For Beginners Course Teaches You The Python Language Fast. Includes Python Online Training With Python 3"
                }
            }
        ],
        "Mobile App Development": [
            {
                "id": 2002,
                "createdOn": 1572528493000,
                "name": "Flutter",
                "description": "Flutter is a mobile technology",
                "createdBy": "DL",
                "approved": true,
                "reason": null,
                "courseStatus": "APPROVED",
                "courseCategory": {
                    "id": 2001,
                    "createdOn": 1572528308000,
                    "category": "Mobile App Development",
                    "description": "Boom in market"
                }
            }
        ],
        "Automation Testing": [
            {
                "id": 1950,
                "createdOn": 1572435931000,
                "name": "Selenium",
                "description": "It's a automation testing tool for web",
                "createdBy": "opp",
                "approved": true,
                "reason": "fvgbhnj",
                "courseStatus": "APPROVED",
                "courseCategory": {
                    "id": 1915,
                    "createdOn": 1572421405000,
                    "category": "Automation Testing",
                    "description": "\"TOP RATED (BEST SELLER) #1 Master SELENIUM java course\" -3 Million students learning worldWide with great collaboration"
                }
            },
            {
                "id": 2073,
                "createdOn": 1572611314000,
                "name": "string",
                "description": "string",
                "createdBy": "ski",
                "approved": true,
                "reason": null,
                "courseStatus": "APPROVED",
                "courseCategory": {
                    "id": 1915,
                    "createdOn": 1572421405000,
                    "category": "Automation Testing",
                    "description": "\"TOP RATED (BEST SELLER) #1 Master SELENIUM java course\" -3 Million students learning worldWide with great collaboration"
                }
            }
        ]
    },
    "message": "Success",
    "timestamp": 1573199357155,
    "status": 200,
    "isSuccess": true
}

但是我在解析 JSON 响应时遇到了一个错误

if let r = StudentTopCouses.init(JSON: data), let result = r.results {
     for (key, value) in result {
         print("Key: \( key )" )
         print("Course Name: \( value.first!.name! )")
     }
}

错误信息:

调用中的参数标签不正确(有 'JSON:',预期为 'map:') 将“JSON”替换为“地图”

【问题讨论】:

  • 而不是SwiftyJSON ObjectMapper 使用Codable。它是内置的、高效的、易于使用的,并且没有依赖项。如果有本地对应物(IntBool),请不要在 Swift 中使用 NS.. 类。对于动态类型,请使用泛型、具有关联类型的枚举或自定义 init(from decoder 实现。

标签: ios swift


【解决方案1】:

您应该阅读文档:https://github.com/tristanhimmelman/ObjectMapper

StudentTopCouses 构造函数是 init?(map: Map) 不是 init(JSON: ...)

所以在线上的错误是正确的:let r = StudentTopCouses.init(JSON: data) where you don't have such a constructor..

Mappable 协议如下(根据上面 Mappable.swift 中的链接):

public protocol Mappable: BaseMappable {
    init?(map: Map)
}

根据上面的文档,您必须这样做:

if let studentTopCourses = Mapper&lt;StudentTopCourses&gt;().map(JSONObject: SomeJSONDictionary)

或:

if let studentTopCourses = Mapper&lt;StudentTopCourses&gt;().map(JSONString: SomeJSONString)

编辑:由于您使用的是SwiftyJSON 库和ObjectMapper 库,因此您需要对它们进行接口:

if let jsonString = data.rawString(), let r = Mapper<StudentTopCouses>.map(JSONString: jsonString)

或:

//Can use JSON or JSONObject here..
if let jsonDict = data.dictionaryObject(), let r = Mapper<StudentTopCouses>.map(JSON: jsonDict)

【讨论】:

  • 怎么办??因为我无法处理这个 JSON 响应。请提出更好的方法。
  • 我添加了对该问题的答案,但您确实需要阅读您决定使用的库的文档。将您的数据转换为字符串或字典,然后使用适当的 Mapper 函数.
  • 有没有更好的方法来处理这个 API 响应。如果是,请提出建议,因为我仍然遇到问题。
  • 那你又做错了。据我所知,您有某种名为JSON 的对象。如果我假设这是SwiftyJSON,那么您需要在调用 ObjectMapper 之前进行转换。这意味着您需要执行以下操作:data.dictionaryObjectdata.rawString 然后调用 ObjectMapper.. 似乎您正在使用相当多的库并且只是希望事情能够正常工作:l 您确实需要阅读错误。我们无法猜测您遇到的其他错误,而此答案无法解决。它绝对解决了您的问题,仅此而已。
  • 是的,谢谢@Brandon。你说得对,我使用的是 swiftyJSON 和 Object Mapper。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-07
  • 1970-01-01
  • 1970-01-01
  • 2017-12-16
  • 1970-01-01
  • 1970-01-01
  • 2019-12-27
相关资源
最近更新 更多