I want to send String JSON array as parameter, but only dictionary [String:AnyObject] format is supported. How am I supposed to convert JSON array into [String:AnyObject]?
I'm new to Swift language and have experience in Java. I'm using ObjectMapper for JSON mapping.
@jimmy0251 the parameters var is the dictionary containing ALL parameters and their values.
In this case if you want to send an array as parameter; e.g. [String] or something along those lines you would need to pass it like this:
var parameters: [String: AnyObject]? {
switch self {
case .ArrayParameter: return [ "parameterName": arrayObject ]
}
}
That means that the parameter called parameterName will contain the arrayObject.
Let me know if that helps and if not we can dig it up until you got it up and running
@esttorhe that sends a JSON dictionary of { "parameterName": ... }, but what if you wanted to send a JSON _array_ instead? [ ... ] for example. I don't think that's currently possible in Moya without using a .Custom parameter encoding.
@ashfurrow yeah I was working under the assumption that perhaps Jimmy wanted to send an array as a parameter.
If what he wants is send a JSON array then yeah I guess .Custom would be needed.
Maybe let's wait until he can clarify if he meant the array parameter or the parameters as an array 😄
Yeah, good thinking. JSON-arrays-as-data is a personal pet peeve – I really wish API developers would stop doing it :disappointed:
Same here but maybe there's a really good and valid scenario for something like that (although I haven't found one just yet).
@esttorhe Actually I want to send JSON Array. I guess I have to go with .Custom parameter encoding.
Here's my solution for sending JSON array to server. Suggestions are welcome as I'm new to Moya.
Define JsonArrayEncoding closure:
let JsonArrayEncodingClosure: (URLRequestConvertible, [String:AnyObject]?) -> (NSMutableURLRequest, NSError?) = { request, data in
var req = request.URLRequest as NSMutableURLRequest
do {
let json = try NSJSONSerialization.dataWithJSONObject(data!["jsonArray"]!, options: NSJSONWritingOptions.PrettyPrinted)
req.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
req.HTTPBody = json
} catch {
return (req, nil)
}
return (req, nil)
}
Configure target :
var parameters: [String:AnyObject]? {
switch self {
case .SomeAPI:
return ["jsonArray": ["Yes", "What", "Abc"]]
default:
return nil
}
}
var parameterEncoding: Moya.ParameterEncoding {
switch self {
case .SomeAPI:
return ParameterEncoding.Custom(JsonArrayEncodingClosure)
default:
return ParameterEncoding.JSON
}
}
Great solution @jimmy0251! Thanks a lot for sharing, I'm sure this will help others :bow: Do you consider the issue closed at this point, or do you think we should add your solution to our documentation, etc? Maybe something for #466.
I got you covered, added this example to PR, commit authorship set to @jimmy0251:)
Thanks a lot @ealeksandrov and @ashfurrow for adding it to examples. I think we should close the issue now.
Encountered the same problem and had maybe an obvious question - where should I put var parameterEncoding: Moya.ParameterEncoding ? It is not part of the TargetType protocol, so adding it to my endpoints struct does nothing.
Until now, I was making my own Endpoint in endpointClosure, but it seems a bit too complicated to simply have different parameter encoding.
In fact, it's how you should approach this, @vytis 🐼 More about it here.
I thought I was missing something, thanks for clarification!
Has anyone figured out how to do this with swift 3.0?
@tdouglas1313 Hmm, it should be possible to do it the same way, using endpointClosure. Did you encounter any problems with that? If so, please open another issue targeting Swift 3.0 version :)
ParameterEncoding is no longer an enum its a protocol. would you still like me to open an issue?
Yeah, you can pass it as JSONEncoding.default, URLEncoding.default etc., instead of an enum case.
Thanks I did't see that.
No probs! Happy to help! 👊
Here is an UNTESTED example that at least compiles.
extention MyService: TargetType {
...
var parameters: [String:AnyObject]? {
switch self {
case .SomeAPI:
return ["jsonArray": ["Yes", "What", "Abc"]]
default:
return nil
}
}
var parameterEncoding: Moya.ParameterEncoding {
switch self {
case .patient_Notifications_Create_Endpoint:
return JsonArrayEncoding.default
default:
return JSONEncoding.default
}
}
...
}
struct JsonArrayEncoding: Moya.ParameterEncoding {
public static var `default`: JsonArrayEncoding { return JsonArrayEncoding() }
/// Creates a URL request by encoding parameters and applying them onto an existing request.
///
/// - parameter urlRequest: The request to have parameters applied.
/// - parameter parameters: The parameters to apply.
///
/// - throws: An `AFError.parameterEncodingFailed` error if encoding fails.
///
/// - returns: The encoded request.
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var req = try urlRequest.asURLRequest()
let json = try JSONSerialization.data(withJSONObject: parameters!["jsonArray"]!, options: JSONSerialization.WritingOptions.prettyPrinted)
req.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
req.httpBody = json
return req
}
}
In my case, it work with below code:
public var parameterEncoding: ParameterEncoding {
switch self {
case .submitForm:
return PropertyListEncoding.default
default:
return URLEncoding.default
}
}
update:
Later, my way isn't worked, i think bcz have some change in server. So now the way of @tdouglas1313 worked for me.
Hai ,My Json dict is as follows
After decoding of Json, How to get this details in a single tableview ,any one help me
How can i create json module also
thanks!
[{"StudentID":2451,"ClassID":49,"SectionID":404,"Total":75.0,"Percentage":62.5,"Result":"PASS","RankGrade":"D","subjectmarks":[{"SubjectID":158,"SubjectCode":"TAM","SubjectName":"TAMIL","Mark":4.5},{"SubjectID":159,"SubjectCode":"ENG","SubjectName":"ENGLISH","Mark":8.5},{"SubjectID":160,"SubjectCode":"HIN","SubjectName":"HINDI","Mark":15.0},{"SubjectID":161,"SubjectCode":"MAT","SubjectName":"MATHS","Mark":12.5},{"SubjectID":165,"SubjectCode":"SCE","SubjectName":"SCEINCE","Mark":17.0},{"SubjectID":166,"SubjectCode":"SOC","SubjectName":"SOCIAL SCIENCE","Mark":17.5}],... }]
@masthanl Is this a question for the Moya library?
Just creaate my custom encoding in task

:
let encoding = URLEncoding(destination: .methodDependent, arrayEncoding: .noBrackets, boolEncoding: .numeric)
All parameters we can change
Most helpful comment
Here is an UNTESTED example that at least compiles.