The Crystal Programming Language Forum

Using from_json method of a class with a post request

Sorry in advance for not including a working example. Hoping if someone is aware of the issue and can answer without a working example.

I have a struct, say

struct User
     JSON.mapping(
               name: String?,
               email: String,
               hobbies: Array(String)?
    )
end

I make a json post request from the client to the server (a route in Kemal) that contains the user’s information. Option 1 below fails, while option 2 works. Any ideas why Option 1 is failing? Why do I have to do JSON.parse(postbody).to_json for it to work. I am worried that the solution may not be robust. Would really appreciate any help.

Option 1 (errors out with: Unexpected token: EOF at 1:1)

postbody = env.request.body.not_nil!
user = User.from_json(postbody)

Option 2 (this works)

postbody = env.request.body.not_nil!   
modpostbody = JSON.parse(postbody).to_json
user = User.from_json(postbody)

Thank you.

What’s the post request body?

Hi @asterite,

The post request body is supposed to be a json body containing the user object (I am using Elm on the frontend to create the json).

So it looks like

{"name": "Crystal", "email": "crystal@example.com", "hobbies": ["fast", "fun", "resourceful"}

This is the output in the terminal when I invoke puts JSON.parse(postbody) (which works):

{“name” => “Crystal”, “email” => "crystal@example.com", “hobbies” => [“fast”, “fun”, “resourceful”]}

I can’t reproduce the problem using HTTP::Server.

Could you provide the full code? Like runnable code that I can download, just do crystal some_file.cr and then provide the curl line or whatever method you are feeding data to the server?

Thank you @asterite. I will try to make a runnable version and post it.

Hi @asterite

Sorry for not posting a runnable version yet. But I wanted to point out that I figured out the issue (it was my mistake). I think the problem was that I was actually doing the following to check the post request.

postbody = env.request.body.not_nil!
puts JSON.parse(postbody) ## this empties the postbody
user = User.from_json(postbody) ##Now that the postbody is empty, I get EOF error

Wouldn’t it be better to copy the postbody when passed to a function like this, so that this does not occur inadvertently? Probably it is not very efficient.

Thanks.