XYJSON
创建请求参数的简单方法。
需求
- iOS 8.0+
- Swift 5.1+
- Xcode 11.0+
安装
使用 CocoaPods 安装
pod 'XYJSON'
使用 Carthage 安装
github "RayJiang16/XYJSON"
使用方法
JSONParameters
遵循 JSONParameters
结构体或类的声明,您可以使用 requestParameters
免费使用。
struct Employee: JSONParameters {
var name: String
var age: Int
}
let employee = Employee(name: "Tom", age: 21)
print(employee.requestParameters)
// {"name":"Tom", "age":21}
JSONProperty
您模型中的属性名(例如本例中的name
),可能不与请求中的名称相同。您可以使用@JSONProperty
进行重命名。
struct Employee: JSONParameters {
@JSONProperty(name: "employee_name")
var name: String
var age: Int
}
let employee = Employee(name: "Tom", age: 21)
print(employee.requestParameters)
// {"employee_name":"Tom", "age":21}
JSONIgnore
您可以使用@JSONIgnore
来忽略您不希望在请求参数中出现的属性。
struct Employee: JSONParameters {
@JSONProperty(name: "employee_name")
var name: String
var age: Int
@JSONIgnore()
var other: String = ""
}
let employee = Employee(name: "Tom", age: 21)
print(employee.requestParameters)
// {"employee_name":"Tom", "age":21}
JSONValue
枚举
如果您想在模型中使用枚举,则需要确保枚举符合JSONValue
。
enum Sex: Int, JSONValue {
case girl = 0
case boy
}
struct Employee: JSONParameters {
var name: String
var sex: Sex
}
let employee = Employee(name: "Tom", sex: .boy)
print(employee.requestParameters)
// {"name":"Tom", "sex":1}
自定义模型
如果您想在模型中使用另一个结构体或类,则需要确保模型符合JSONValue
并实现var jsonValue: JSONValue
。
enum Sex: Int, JSONValue {
case girl = 0
case boy
}
struct Employee: JSONParameters {
var name: String
var sex: Sex
var test: Test = Test()
}
struct Test: JSONValue, JSONParameters {
var t1: Int = 1
var t2: String = "t2"
var jsonValue: JSONValue {
// You can return Int, Double, Array, Dictionary...
return requestParameters
}
}
let employee = Employee(name: "Tom", sex: .boy)
print(employee.requestParameters)
// {"name":"Tom", "sex":1, "test":{"t1":1, "t2":"t2"}}
注意
当您使用@JSONProperty
或@JSONIgnore
时,需要重写init
函数。默认的init
函数不适用,因为实际上@propertyWrapper
是struct
。
在init
函数中,如果您的模型中没有为该属性设置默认值,则应该将带有@JSONProperty
或@JSONIgnore
的属性设置在最后。
struct Employee: JSONParameters {
@JSONProperty(name: "employee_name")
var name: String
var age: Int
init(name: String,
age: Int) {
self.age = age
self.name = name
}
}
请不要在同一个模型中同时使用XYJSON
和HandyJSON
,否则HandyJSON
将无法正常工作。因为实际上@propertyWrapper
是struct
。
许可证
XYJSON 受MIT许可证保护。更多信息请查看许可证文件。