How to use Alamofire with JSONDecoder? - alamofire

I am try to parsing google Direction API as below.
https://developers.google.com/maps/documentation/directions/start
but unable to get any result from JSONDecoder , it always return Error block
I am using Alamofire code as below for parsing .
let decoder = JSONDecoder()
do {
let userDictionary = try decoder.decode(DirectionParser.self, from: response.data!)
print("The Parser \(userDictionary)")
} catch {
print("Error")
}

I think you are doing right. Just make sure you are trying to parse what you want. You can do this by printing out
print(response.anythingYouWant)
Can you show us DirectionParser.
Make sure it is like below code
struct DirectionParse: Decodable {
//things you want to fetch
}
P.S I would have commented if I had reputation 50+.

Related

Is Mono's share().block() non-blocking?

I am in the middle of learning Spring WebFlux. I am using a REST call using below code to parse the response:
private void parseJsonResponse(String folderId) throws IOException {
Mono<ObjectNode> theresponseMono = webClient.get()
.uri("/some/uri")
.retrieve().bodyToMono(ObjectNode.class);
ObjectNode node = new ObjectMapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.readValue(theresponseMono.share().block().toString(), ObjectNode.class);
//handle node object here.....
}
Question: Is theresponseMono.share().block() non-blocking here? If not, what can be done to make is completely non-blocking. I am looking for the relevant documentation on this as I want to learn it and not just looking for a yes or no. To summarize, I need to retrieve theresponseMono as non-blocking. Any guidance or any official documentation/link on this please? Thanks.
EDIT:
This is what I am trying to achieve:
Mono<ObjectNode> theresponseMono = webClient.get()
.uri("/some/uri")
.retrieve().bodyToMono(ObjectNode.class).flatMap(node -> {
if (node.get("list").get("entries").isArray()) {
for (JsonNode jsonNode : node.get("list").get("entries")) {
System.out.println(jsonNode);
}
}
});
Somehow I am not able to map using flatMap. What is missing here?
No since here you are blocking it. Right way would be to do
private Mono<ObjectNode> parseJsonResponse(String folderId) {
return webClient.get()
.uri("/some/rui")
.retrieve().bodyToMono(ObjectNode.class)
.flatMap(node-> {
// do your logic here
})
}
I would say everything what is in mono/flux must stay in mono/flux :) Anytime you call block its blocking your thread.

Kotlin: lambda run alternative scenario

I have userDto, contains programs, which contains actual field. Actual program can be only one. I need to get it. Than, I run this:
userDto.programs.sortedBy { it.created }.findLast { it.actual }?
Okay, but I want to foresee case, when findLast returns null, & throw exception. Please, advice, how to do it?
UPD:
ProgramType.valueOf(userDto.programs
.sortedBy { it.created }
.findLast { it.actual }
//check here
!!.programType!!).percentage
You are pretty close actually :)! What you could do is:
userDto.programs.sortedBy { it.created }.findLast { it.actual } ?: throw RuntimeException()
Or if you're trying to actually avoid throwing an error(couldn't really tell with the way question is asked), you could just do an error check like this:
userDto.programs.sortedBy { it.created }.findLast { it.actual }?.let{
//rest of your code goes here
}
Hope this helps, cheers!

RxAlamofire: Ambiguous reference to member 'json(_:_:parameters:encoding:headers:)'

When I try to compile the code below, I get an error:
Ambiguous reference to member 'json(::parameters:encoding:headers:)'
The code was copied and pasted from a RxAlamofire Github repository page
import RxSwift
import RxAlamofire
class CurrencyRest {
static func getJson() {
let stringURL = "https://api.fixer.io/latest"
// MARK: NSURLSession simple and fast
let session = URLSession.init()
_ = session.rx.json(.get, stringURL)
.observeOn(MainScheduler.instance)
.subscribe { print($0) }
}
}
To fix the error, session.rx.json(url:) is the way to go, it's from RxCocoa, although for RxAlamofire, you don't have to use URLSession rx extension, instead, use json(::parameters:encoding:headers:), e.g. json(.get, stringURL), which returns an Observable<Any> that you can use as JSON.

what is the proper syntax for the following expression in swift 3?

as you can guess, this is an issue regarding swift's whole API renovation. I've read the documentation extensively but can't seem to lay my finger on a proper workaround.
I am receiving the error
Value of type 'Error' has no member 'userInfo'
on the following line:
else if let secondMessage = error?.userInfo["error"] as? String
of this block:
let query = PFQuery(className: "Images")
query.whereKey("Subject", equalTo: self.subjectName)
query.findObjectsInBackground { (objects, error) -> Void in
if error == nil {
// do something
}else if let secondMessage = error?.userInfo["error"] as? String {
// do something
}
Any suggestions? feel's like I'm missing something painstakingly obvious... dev block i guess :(

Alamofire put request

Try to get Alamofire put request to work, but system shows "Extra Argument in Call"
Alamofire.request(.PUT, apiUrl,params,ParameterEncoding.JSON)
.responseJOSN{ (request, response, products: [Product]?,error) in
println(request)
println(response)
println(data)
println(error)
}
Anyone can solve this problem?
You have multiple issues in your code sample. Here's a corrected version that should get you going:
let apiURLString = "whatever/your/url/is"
let parameters: [String: AnyObject] = [:] // fill in your params
let request = Alamofire.request(.PUT, apiURLString, parameters: parameters, encoding: .JSON)
request.responseJSON { request, response, json, error in
println(request)
println(response)
println(json)
println(error)
}
I would also encourage you to really read through the Alamofire README in depth. It has some great information and should make it much easier for you to get the basics working.
As 'alamofire' '~2.0' has changed the in number of parameters
You can try with the following block of code:
Alamofire.request(.PUT,apiUrl,params).responseJSON { request, response, result in
print(request)
print(response)
print(result.value)
if(result.isSuccess){
//Do in success block
}else{
//Do in failure block
}
}
Alamofire.request does not have error handler parameter available, hence it was showing you that "Extra Argument in Call"