Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

post request body #22

Closed
loganwright opened this issue Feb 13, 2016 · 5 comments
Closed

post request body #22

loganwright opened this issue Feb 13, 2016 · 5 comments

Comments

@loganwright
Copy link
Member

When receiving a JSON request, I expected the request.data to include the keys and values, but instead it's a json string key and value that are identical, ie:

["{\"hello\":\"world\"}" : "{\"hello\":\"world\"}"]

@tanner0101
Copy link
Member

Vapor currently only supports form encoded data. Issue #28 covers supporting JSON requests.

@loganwright
Copy link
Member Author

@tannernelson Cool, in the meantime, here's two different examples that work:

In case it helps, these are both functioning for me:

extension Request {
    public var jsonBody: Any? {
        var bytes = body
        let data = NSData(bytes: &bytes, length: body.count)
        return try? NSJSONSerialization
            .JSONObjectWithData(data, options: .AllowFragments)
    }
}

Or w/ pure json dependency:

.Package(url: "https://github.com/gfx/Swift-PureJsonSerializer", majorVersion: 1)
extension Request {
    public var jsonBody: Json? {
        return try? Json.deserialize(body)
    }
}

@tanner0101
Copy link
Member

Does that compile on Ubuntu 14, 15, and OS X?

If so, you should submit that as a PR.

@loganwright
Copy link
Member Author

@tannernelson

They both work on Heroku box, but the NSJSON version is relatively useless for anything but printing. It doesn't like it if I cast to [String : Any], and it doesn't like it if I cast to [String : AnyObject] on linux.

I think until Foundation adds official support, it might be worth using, or pointing to a 3rd party dependency. The PureJson version above runs on all instances and in my opinion, is a better way to deal with Json.

If you're interested in that, I can make a pull that includes the dependency. It's a little slower than NSJSON, but you also get the added benefit of being able to return:

return json.serialize(.PrettyPrint)

Which serializes more effectively

@tanner0101
Copy link
Member

The NSJSON from Foundation won't work because it relies on the automatic casting of any Array or Dictionary to an NSArray or NSDictionary. I don't know if that's something that will ever be added to Linux.

So I think a dependency makes sense for serialization on Linux. If Apple does decide to include Foundation support at some point it can be removed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants