首页 > 解决方案 > 如何在 swift 5 中使用动态键处理对象映射

问题描述

我正在尝试使模型类使用动态键及其值来处理 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"]
  }
}

顶级课程 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' 替换为 'map'

标签: iosswift

解决方案


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

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

所以在线上的错误是正确的:let r = StudentTopCouses.init(JSON: data)你没有这样的构造函数..

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

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

根据上面的文档,您必须执行以下操作:

if let studentTopCourses = Mapper<StudentTopCourses>().map(JSONObject: SomeJSONDictionary)

或者:

if let studentTopCourses = Mapper<StudentTopCourses>().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)

推荐阅读