Par*_*n V 4 json ios swift alamofire jsondecoder
这是我的JSON响应值:
{
"_embedded": {
"task": [
{
"_embedded": {
"variable": [
{
"_links": {
"self": {
"href": "/process-instance/412a03b7-06ae-11ea-8860-120ef5ab2c25/variables/loanAmount"
}
},
"_embedded": null,
"name": "loanAmount",
"value": "650000",
"type": "String",
"valueInfo": {}
}
]
},
"id": "412a2aca-06ae-11ea-8860-120ef5ab2c25",
"name": "Quick Evaluation",
"assignee": "demo",
"created": "2019-11-14T07:13:27.558+0000",
"processDefinitionId": "quickEvaluation:1:129ce2b1-0616-11ea-8860-120ef5ab2c25"
}
]
},
"count": 13
}
Run Code Online (Sandbox Code Playgroud)
这是struct可编码的代码:
import Foundation
public struct TaskID: Codable {
let embedded: Embedded
}
public struct Embedded: Codable {
let task: [Task]
}
public struct Task : Codable {
let embedded: EmbeddedVariable
let id : String
let name: String
let assignee: String
let created: String
let processDefinitionId: String
}
public struct EmbeddedVariable: Codable {
let variable : [Variables]
}
public struct Variables: Codable {
let value : String
let name: String
}
Run Code Online (Sandbox Code Playgroud)
我已经尝试过encodingKey,也尝试过使用_embedded。面对同样的问题。
错误日志:由于错误,无法解码响应:
Alamofire.AFError.
ResponseSerializationFailureReason.decodingFailed(error: Swift.DecodingError.typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil)))))
Run Code Online (Sandbox Code Playgroud)
数据格式不正确,因此无法读取。
这是JSONSerialization的代码:
// MARK: - URLRequestConvertible
func asURLRequest() throws -> URLRequest {
let url = try K.ProductionServer.baseURL.asURL()
var urlRequest = URLRequest(url: url.appendingPathComponent(path))
print(urlRequest)
// HTTP Method
urlRequest.httpMethod = method.rawValue
let authToken = UserDefaults.standard.string(forKey: "authToken")
let bearerToken: String = "Bearer " + (authToken ?? "")
print("baearer token::\(bearerToken)")
// Common Headers
urlRequest.setValue(ContentType.json.rawValue, forHTTPHeaderField: HTTPHeaderField.acceptType.rawValue)
urlRequest.setValue(ContentType.json.rawValue, forHTTPHeaderField: HTTPHeaderField.contentType.rawValue)
urlRequest.setValue(bearerToken, forHTTPHeaderField: HTTPHeaderField.authentication.rawValue)
// Parameters
if let parameters = parameters {
do {
urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: [])
} catch {
throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
}
}
return urlRequest
}
Run Code Online (Sandbox Code Playgroud)
这是代码json返回响应:
import Foundation
import Alamofire
public class APIClient {
@discardableResult
private static func performRequest<T:Decodable>(route:APIRouter, decoder: JSONDecoder = JSONDecoder(), completion:@escaping (AFResult<T>)->Void) -> DataRequest {
return AF.request(route)
.responseDecodable (decoder: decoder){ (response: AFDataResponse<T>) in
completion(response.result)
print("framework response::",response.result)
}
}
public static func taskID(id: String, completion:@escaping (AFResult<MyTaskData>)->Void) {
performRequest(route: APIRouter.TaskById(id: id), completion: completion)
}
}//APIClient
Run Code Online (Sandbox Code Playgroud)
在您的JSON有效负载中,键processDefinitionId的值的末尾有一个逗号。
尝试使用此JSON Formatter工具来验证JSON:jsonformatter
"task":[
{
//...
"id": "412a2aca-06ae-11ea-8860-120ef5ab2c25",
"name": "Quick Evaluation",
"assignee": "demo",
"created": "2019-11-14T07:13:27.558+0000",
"processDefinitionId": "quickEvaluation:1:129ce2b1-0616-11ea-8860-120ef5ab2c25", // remove this coma(,) from this line
}
Run Code Online (Sandbox Code Playgroud)
更新:
使用CodingKey了_embedded。尝试以下方式
// MARK: - TaskID
struct TaskID: Codable {
let embedded: Embedded
let count: Int
enum CodingKeys: String, CodingKey {
case embedded = "_embedded"
case count
}
}
// MARK: - Embedded
struct Embedded: Codable {
let task: [Task]
}
// MARK: - Task
struct Task: Codable {
let embedded: EmbeddedVariable
let id, name, assignee, created: String
let processDefinitionID: String
enum CodingKeys: String, CodingKey {
case embedded = "_embedded"
case id, name, assignee, created
case processDefinitionID = "processDefinitionId"
}
}
// MARK: - EmbeddedVariable
struct EmbeddedVariable: Codable {
let variable: [Variable]
}
// MARK: - Variable
struct Variable: Codable {
let links: Links
let name, value, type: String
let valueInfo: ValueInfo
enum CodingKeys: String, CodingKey {
case links = "_links"
case name, value, type, valueInfo
}
}
// MARK: - Links
struct Links: Codable {
let linksSelf: SelfClass
enum CodingKeys: String, CodingKey {
case linksSelf = "self"
}
}
// MARK: - SelfClass
struct SelfClass: Codable {
let href: String
}
// MARK: - ValueInfo
struct ValueInfo: Codable {
}
Run Code Online (Sandbox Code Playgroud)