Giter Site home page Giter Site logo

about Json Parsing about alamofire HOT 19 CLOSED

alamofire avatar alamofire commented on May 12, 2024
about Json Parsing

from alamofire.

Comments (19)

justinmakaila avatar justinmakaila commented on May 12, 2024

Parsing client specific JSON is beyond the scope of this library, and is a responsibility placed on the specific client. SwiftyJSON is built in a way that lets you turn the JSON object returned from Alamofire into a JSONValue very easily.

Write a class that wraps Alamofire, providing custom GET, POST, etc. methods and use the .response() methods to call a success or failure block as appropriate for your code, passing along the JSON.

from alamofire.

mattt avatar mattt commented on May 12, 2024

Parsing client specific JSON is beyond the scope of this library, and is a responsibility placed on the specific client.

Well said, @justinmakaila.

Though I would say the easiest way to integrate would be to implement a responseSwiftyJSON method in an extension on Alamofire.Request.

from alamofire.

justinmakaila avatar justinmakaila commented on May 12, 2024

I almost forgot about how wonderfully easy it is to do things like that in Swift. Changing my own implementation now!—
Sent from Mailbox

On Tue, Aug 26, 2014 at 2:12 PM, Mattt Thompson [email protected]
wrote:

Parsing client specific JSON is beyond the scope of this library, and is a responsibility placed on the specific client.
Well said, @justinmakaila.

Though I would say the easiest way to integrate would be to implement a responseSwiftyJSON method in an extension on Alamofire.Request.

Reply to this email directly or view it on GitHub:
#57 (comment)

from alamofire.

zhfish avatar zhfish commented on May 12, 2024

responseSwiftyJSON ~~thanks

from alamofire.

LarsJK avatar LarsJK commented on May 12, 2024

Has anyone actually done this?
Having a hard time since JSONValue is of type enum, an does not conform to AnyObject. Is there an easy way to implement this?
Could Alamofire make it easier to implement, by allowing Any in Request.response instead of AnyObject..

from alamofire.

justinmakaila avatar justinmakaila commented on May 12, 2024

I have an implementation, I can post it later tonight—
Sent from Mailbox

On Sat, Sep 20, 2014 at 6:19 PM, Lars-Jørgen Kristiansen
[email protected] wrote:

Has anyone actually done this?

Having a hard time since JSONValue is of type enum, an does not conform to AnyObject. Is there an easy way to implement this?

Reply to this email directly or view it on GitHub:
#57 (comment)

from alamofire.

justinmakaila avatar justinmakaila commented on May 12, 2024
import Alamofire

// MARK: Alamofire Extensions

typealias AlamofireResponseCompletionBlock = (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void

typealias APIResourceResponseCompletionBlock = (NSURLRequest, NSHTTPURLResponse?, JSONValue?, NSError?) -> Void
typealias APICollectionResponseCompletionBlock = (NSURLRequest, NSHTTPURLResponse?, [JSONValue]?, Int?, NSError?) -> Void

internal extension Alamofire.Request {
    func collectionResponseJSON(completionHandler: APICollectionResponseCompletionBlock) -> Self {
        let completion: AlamofireResponseCompletionBlock = { request, response, JSON, error in
            var jsonData: JSONValue!,
                results: [JSONValue]?,
                nextCursor: Int!,
                requestError: NSError?

            if let data: AnyObject = JSON {
                jsonData = JSONValue(data)

                if error != nil {
                    requestError = self.serializeRequestError(jsonData, error: error!)
                } else {
                    results = jsonData["results"].array
                    nextCursor = jsonData["nextCursor"].integer
                }
            }

            dispatch_async(dispatch_get_main_queue(), {
                completionHandler(request, response, results, nextCursor, (requestError != nil) ? requestError! : error)
            })
        }

        return response(
            priority: 0,
            queue: APIManager.sharedInstance().callbackQueue,
            serializer: Request.JSONResponseSerializer(),
            completionHandler: completion
        )
    }

    func resourceResponseJSON(completionHandler: APIResourceResponseCompletionBlock) -> Self {
        let completion: AlamofireResponseCompletionBlock = { request, response, JSON, error in
            var jsonData: JSONValue!,
                requestError: NSError?

            if let data: AnyObject = JSON {
                jsonData = JSONValue(data)

                if error != nil || response?.statusCode >= 300 {
                    requestError = self.serializeRequestError(jsonData, error: error)
                }
            }

            dispatch_async(dispatch_get_main_queue(), {
                completionHandler(request, response, jsonData, (requestError != nil) ? requestError! : error)
            })
        }

        return response(
            priority: 0,
            queue: APIManager.sharedInstance().callbackQueue,
            serializer: Request.JSONResponseSerializer(),
            completionHandler: completion
        )
    }

    /**
    *  Attempts to serialize error json into an NSError object.
    *  @discussion If `json` is nil, returns `error`
    *
    *  @param json JSONValue representing the error
    *  @param error NSError that came back from Alamofire
    *
    *  @return NSError with JSON error serialized in userInfo["APIError"]
    */
    private func serializeRequestError(json: JSONValue?, error: NSError?) -> NSError? {
        var apiError: Error?,
            requestError: NSError? = error

        if let jsonError: JSONValue = json {
            apiError = Error(json: jsonError)
        }

        if apiError != nil {
            requestError = NSError(domain: "APIManagerErrorDomain", code: apiError!.code ?? -1111, userInfo: [
                "APIError": apiError!
                ])
        }

        return requestError
    }
}

from alamofire.

justinmakaila avatar justinmakaila commented on May 12, 2024

^ @iUtvikler

from alamofire.

LarsJK avatar LarsJK commented on May 12, 2024

@justinmakaila Works great! Thanks

from alamofire.

harshcs avatar harshcs commented on May 12, 2024

I have been looking since a days on "How to parse JSON response from Alamofire API in Swift?" but didn't get the answer yet! Please take a look on the below code and let me know what has o be done in this regard.
Alamofire.request(.POST, "MY URL", parameters:parameters, encoding: .JSON) .responseJSON
{
(request, response, JSON, error) in

println(JSON?)

}
I am able to print the response but cannot assign in Dictionary or Array. Why so?
How can I parse the response from this method?

from alamofire.

Baza207 avatar Baza207 commented on May 12, 2024

I use something like the following. I'm not sure if it's the best way of doing it, but it seems to work for me.

Alamofire.request(.POST, "MY URL", parameters:parameters, encoding: .JSON)
    .responseJSON { (request, response, json, error) in
        if let object = json as? NSDictionary {
            println(object)
        }
}

This gives you a non-optional constant called object that you can then do with as you will.

It does however mean you have to know if your base structure is an array or a dictionary, so there are probably better ways of doing it to make it more abstract.

from alamofire.

harshcs avatar harshcs commented on May 12, 2024

Thanks for your answer!
I tried that and I am able to print that object also but still I am facing issues in assigning the value from the Dictionary in the String form.
I am getting following response
{
message = "succesfull login";
sid = "";
status = 1;
}

and I am trying something like this.
if var dictionary = JSON as? NSDictionary
{
println(dictionary) //1

            println(dictionary.objectForKey("status"))  //2

            var temp:String = dictionary.objectForKey("status")  //2                
        }

On line //3, I am getting following error,
Cannot convert the expression's type 'StaticString' to type 'AnyObject'

How can I store value in String so that I can use that? Why this all is so complex?

from alamofire.

violabg avatar violabg commented on May 12, 2024

You should take a look at https://github.com/SwiftyJSON/SwiftyJSON

there is also an extension to work with Alamofire

https://github.com/SwiftyJSON/Alamofire-SwiftyJSON

from alamofire.

Baza207 avatar Baza207 commented on May 12, 2024

You have to take it out as a string. So try something like the following.

var temp = dictionary.objectForKey("status") as? String

This will give you an optional String variable in temp.

I might be wrong but this type of questioning might be better moved to StackOverflow or similar places. As issues for Git repos are normally more for issue/bugs with the framework rather than use issues.

from alamofire.

harshcs avatar harshcs commented on May 12, 2024

I tried this
var temp = dictionary.objectForKey("status") as? String
and it is returning nil but there is a value for the key "status".
Yes, I should ask that on Stackoverflow and I have posted my questions over there but nobody responded. That is why I here as I downloaded Alamofire from here.

And my question is very simple and I am surprised why nobody can answer this.

from alamofire.

harshcs avatar harshcs commented on May 12, 2024

@violabg
https://github.com/SwiftyJSON/Alamofire-SwiftyJSON
I downloaded that but SwiftJSON folder is empty and seems files are missing
Can you please let me know how can I use that?

from alamofire.

Baza207 avatar Baza207 commented on May 12, 2024

@harshcs My guess would be look into submodules in Git, I think that would be why you have an empty folder.

I've just noticed that your "status" value is an integer in the sample JSON you provided, not a String as you're trying to cast it as. So taking it out and casting as a String will return nil as it can't find a String so it returns nil. Try the following to get an optional Int:

let temp = dictionary.objectForKey("status") as? Int

Make sure you always double check what type the JSON value is. If you want to make it into a string this you could do something like the following:

let tempString = String(temp)

from alamofire.

harshcs avatar harshcs commented on May 12, 2024

@Baza207 aka James! 👍
Thanks a lot Baza! Actually server side developer sending the Bool value and internally it was getting converted in the Integer form but now it is working as I put a check for the Int value and its not Nil anymore. You saved me! :-)

from alamofire.

thihaaung6245 avatar thihaaung6245 commented on May 12, 2024

@harshcs can you describe the implementation that you did.
I am newbie to swift and Alamofire

from alamofire.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.