Moya-ModelMapper
Moya-ModelMapper copied to clipboard
Map Dictionary
{
"args": {},
"data": "{\n\t\"target\": \"facebook\",\n\t\"token\": \"djkshksgjksgk\",\n\t\"username\": \"thienhaole92\",\n\t\"password\": \"123456\"\n}",
"files": {},
"form": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Cache-Control": "no-cache",
"Connection": "close",
"Content-Length": "104",
"Content-Type": "application/json",
"Host": "httpbin.org",
"Postman-Token": "6e85dedb-6b8c-49fe-8d82-e83e85ea1b1c",
"User-Agent": "PostmanRuntime/7.1.1"
},
"json": {
"password": "123456",
"target": "facebook",
"token": "djkshksgjksgk",
"username": "thienhaole92"
},
"origin": "116.118.112.156",
"url": "https://httpbin.org/post"
}
How can I map json above to an object model? My object model has a variable type is Dictionary. Please help me
let args: [String: Any]?
let headers: [String: Any]?
let origin: String
let url: String
Hey @thienhaole92. This is a body
of your response?
I am testing with httpbin but my respon body is like this. I want to map headers field into a dictionay
@thienhaole92 can you please give me the URL
to httpbin that you use?
@sunshinejr This is my URL to httpbin URL: https://httpbin.org/post Method: POST Parammeters:
{
"target": "facebook",
"token": "djkshksgjksgk",
"username": "thienhaole92",
"password": "123456"
}
Response:
{
"args": {},
"data": "{\n\t\"target\": \"facebook\",\n\t\"token\": \"djkshksgjksgk\",\n\t\"username\": \"thienhaole92\",\n\t\"password\": \"123456\"\n}",
"files": {},
"form": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Cache-Control": "no-cache",
"Connection": "close",
"Content-Length": "104",
"Content-Type": "application/json",
"Host": "httpbin.org",
"Postman-Token": "6e85dedb-6b8c-49fe-8d82-e83e85ea1b1c",
"User-Agent": "PostmanRuntime/7.1.1"
},
"json": {
"password": "123456",
"target": "facebook",
"token": "djkshksgjksgk",
"username": "thienhaole92"
},
"origin": "116.118.112.156",
"url": "https://httpbin.org/post"
}
Okay. I think the most important thing is the type of a dictionary. The issue is rather with mapper
, but switching it to [String: String]
fixes the problem:
struct Post: Mappable {
let args: [String: String]?
let headers: [String: String]?
let origin: String
let url: String
init(map: Mapper) throws {
args = map.optionalFrom("args")
headers = map.optionalFrom("headers")
try origin = map.from("origin")
try url = map.from("url")
}
}
Let me know if it solves your issue 🌞
If I switch to [String : String]
I can not map dictionary to object if it has Number or somethings else
Yes, but this is one of the few types that mapper
supports. See this function. And this is the list of default convertibles.
As a workaround you could use NSDictionary?
instead of [String: String]
.
please did you find a solution for this problem ? @thienhaole92