简体   繁体   English

在Xcode中构建项目时如何从XML或Json生成swift类或对象

[英]How to generate swift class or object from XML or Json when build project in Xcode

I have a json file with the format like this:我有一个格式如下的json文件:

    {
    "id":"nav_grap",
    "startDestination":0,

    "navigators":[

        {
            "id":0,
            "groupsId":"0",
            "controller_name":"LoginScreen",
            "titleVi":"login_screen",
            "titleEn":"Dang nhap",
            "actions":[{
            "name":"idaction_loginScreen_to_homeScreen",
            "destination":1

            }]},
       {
            "id":1,
            "groupsId":"1",
            "controller_name":"HomeScreen",
            "titleVi":"Cong viec",
            "titleEn":"Jobs",
            "actions":[]
       },
       {
            "id":2,
            "groupsId":"2",
            "controller_name":"NewsScreen",
            "titleVi":"Tin tuc",
            "titleEn":"News",
            "actions":[]
       },
       {
            "id":3,
            "groupsId":"3",
            "controller_name":"BiometricsScreen",
            "titleVi":"Sin trac hoc",
            "titleEn":"News",
            "actions":[]
       },
       {
            "id":4,
            "groupsId":"4",
            "controller_name":"ContactScreen",
            "titleVi":"Tin tuc",
            "titleEn":"News",
            "actions":[]
       }]
}.       

I want to generate a class or object base on the format of this json file when I build my project so after project built I would have a object with properties like this:我想在构建项目时根据此 json 文件的格式生成一个类或对象,因此在构建项目后,我将拥有一个具有如下属性的对象:

    class ScreenConfig : Decodable{

       var id : String
       var startDestination : Int
       var navigators : [Navigator] = []

       init(id : String, startDestination : Int, navigator : [Navigator]) {
          self.id = id
          self.startDestination = startDestination
          self.navigators = navigator
         }

       init() {
                self.id = ""
                self.startDestination = 0
                self.navigators = []
              }
      }.       

So,could anyone please tell me how can I archive this?那么,谁能告诉我如何存档? thanks.谢谢。

I guess you are finding quicktype-xcode我猜你正在寻找quicktype-xcode

quicktype-xcode: Creating models base on API JSON responses quicktype-xcode:基于 API JSON 响应创建模型

To do it manually, you can use Sourcery or SwiftGen , which can automate daily development processes要手动完成,您可以使用SourcerySwiftGen ,它们可以自动化日常开发过程

You need to write a Xcode plugin for generating JSON to Swift code.您需要编写一个 Xcode 插件来生成 JSON 到 Swift 代码。

So you should build extensions to the source editor in Xcode using XcodeKit.因此,您应该使用 XcodeKit 在 Xcode 中构建源代码编辑器的扩展。

Source editor extensions can read and modify the contents of a source file, as well as read and modify the current text selection within the editor.源编辑器扩展可以读取和修改源文件的内容,以及读取和修改编辑器中的当前文本选择。


struct ScreenConfig: Decodable{

   let id : String
   let startDestination : Int
   let navigators : [Navigator]

}

struct Navigator: Decodable {
    let id: Int
    let groupsId: String
    let controller_name : String


    let titleVi: String
    let titleEn: String
    let actions: [Action]?

}



struct Action: Decodable {
    let name: String
    let destination: Int

}

Test Case:测试用例:

you have a json file named "one.json" in your project bundle, which is configured with your data above你的项目包中有一个名为“one.json”的 json 文件,它是用你上面的数据配置的

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        if let src = Bundle.main.url(forResource: "one", withExtension: "json"){
            do {
                let data = try Data(contentsOf: src)
                let decoder = JSONDecoder()
                let model = try decoder.decode(ScreenConfig.self, from: data)
                print(model.navigators.first?.controller_name ?? "ha ha")

            } catch let error {
                print(error.localizedDescription)
            }
        }
    }
}

Using the http://www.jsoncafe.com使用http://www.jsoncafe.com

struct TestingTest : Codable {

        let id : String?
        let navigators : [TestingNavigator]?
        let startDestination : Int?

        enum CodingKeys: String, CodingKey {
                case id = "id"
                case navigators = "navigators"
                case startDestination = "startDestination"
        }
        init(from decoder: Decoder) throws {
                let values = try decoder.container(keyedBy: CodingKeys.self)
                id = try values.decodeIfPresent(String.self, forKey: .id)
                navigators = try values.decodeIfPresent([TestingNavigator].self, forKey: .navigators)
                startDestination = try values.decodeIfPresent(Int.self, forKey: .startDestination)
        }
}


struct TestingNavigator : Codable {

        let actions : [AnyObject]?
        let controllerName : String?
        let groupsId : String?
        let id : Int?
        let titleEn : String?
        let titleVi : String?

        enum CodingKeys: String, CodingKey {
                case actions = "actions"
                case controllerName = "controller_name"
                case groupsId = "groupsId"
                case id = "id"
                case titleEn = "titleEn"
                case titleVi = "titleVi"
        }

        init(from decoder: Decoder) throws {
                let values = try decoder.container(keyedBy: CodingKeys.self)
                actions = try values.decodeIfPresent([AnyObject].self, forKey: .actions)
                controllerName = try values.decodeIfPresent(String.self, forKey: .controllerName)
                groupsId = try values.decodeIfPresent(String.self, forKey: .groupsId)
                id = try values.decodeIfPresent(Int.self, forKey: .id)
                titleEn = try values.decodeIfPresent(String.self, forKey: .titleEn)
                titleVi = try values.decodeIfPresent(String.self, forKey: .titleVi)
        }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM