Answer the question
In order to leave comments, you need to log in
How to properly parse a Json collection?
Greetings Tell me
how to optimally get to the "Body"
Json values, it looks like this (So it leaves the .net server):
{
"isOk":true,
"result":"[
{
"Name":"file0",
"Size":93316,
"MimeType":"image/jpeg",
"Body":"/9j/4QAYRXIDIwMTAvM..."
},
{
"Name":"file1",
"Size":146597,
"MimeType":"image/jpeg",
"Body": "/9j/4AAQSkZJRgABAgAAA.."
]",
"errorMessage":null
}
Alamofire.request(postURL, method: .post, parameters: parameters, encoding: URLEncoding.default).responseJSON { response in
switch response.result {
case .success:
if let result = response.result.value {
print("\n result:", result)
}
}
}
{
"errorMessage" : null,
"isOk" : true,
"result" : "[{\"Name\":\"file0\",\"Size\":70123,\"MimeType\":\"image\/jpeg\",\"Body\":\"\/9j\/4AAQSkZJRgA....}]
}
guard let jsonResponse = response.result.value as? NSDictionary else { return }
if jsonResponse["result"] != nil {
let res = String(describing: jsonResponse["result"]!)
}
SwiftyJson
, but through it I can not get to the arraysif let value = self.json["errorMessage"]["isOk"]["result"][].array {
print("\n value \(value)")
}
Answer the question
In order to leave comments, you need to log in
I get it in a different order, and sometimes this order changes
SwiftyJSON
you need to get an array , it looks like this:json["result"].arrayValue
I would recommend Codable protocol
let json = "{\"isOk\":true,\"result\":[{\"Name\":\"file0\",\"Size\":93316,\"MimeType\":\"image/jpeg\",\"Body\":\"/9j/4QAYRXIDIwMTAvM...\"},{\"Name\":\"file1\",\"Size\":146597,\"MimeType\":\"image/jpeg\",\"Body\":\"/9j/4AAQSkZJRgABAgAAA..\"}],\"errorMessage\":null}"
let data = json.data(using: .utf8)!
struct APIResponse: Decodable {
let isOk: Bool
let result: [Item]
let errorMessage: String?
struct Item: Decodable {
let name: String
let size: Double
let mimeType: String
let body: String
enum CodingKeys: String, CodingKey {
case name = "Name"
case size = "Size"
case mimeType = "MimeType"
case body = "Body"
}
}
}
let response = try! JSONDecoder().decode(APIResponse.self, from: data)
print(response)
// Output:
// APIResponse(isOk: true, result: [__lldb_expr_33.APIResponse.Item(name: "file0", size: 93316.0, mimeType: "image/jpeg", body: "/9j/4QAYRXIDIwMTAvM..."), __lldb_expr_33.APIResponse.Item(name: "file1", size: 146597.0, mimeType: "image/jpeg", body: "/9j/4AAQSkZJRgABAgAAA..")], errorMessage: nil)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question