dhartwich
dhartwich

Reputation: 398

Rails rendering JSON response with UTF-8

I'm trying to build an API with Rails and been doing quite good so far, however now that I added a record with an Umlaut I come to a Problem where I can't render the JSON anymore and I can't figure out how to solve my problem. Here is what the logs say:

 Completed 500 Internal Server Error in 40ms

JSON::GeneratorError (source sequence is illegal/malformed utf-8):
  app/controllers/api/v1/raids_controller.rb:8:in `index'


  Rendered /usr/local/lib/ruby/gems/2.1.0/gems/actionpack-   
4.1.8/lib/action_dispatch/middleware/templates/rescues/_source.erb (1.4ms)
  Rendered /usr/local/lib/ruby/gems/2.1.0/gems/actionpack-    
4.1.8/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (2.3ms)
 Rendered /usr/local/lib/ruby/gems/2.1.0/gems/actionpack-
4.1.8/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.9ms)
 Rendered /usr/local/lib/ruby/gems/2.1.0/gems/actionpack-
4.1.8/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout     
(30.2ms)

And this is the method inside my controller that produces this output:

def index
  #This is the default call and should list all tournaments.
  @tournaments = Tournament.all
  @tournaments = @tournaments.order("startdate DESC")

  respond_to do |format|
    format.json { render :json => @tournaments }
  end
end

Would be awesome if someone could help me to solve my problem. I already checked and I'm sure that UTF-8 encoding is used everywhere. Also if I check through rails console I see that the Character Ü is encoded as name: "\xDC"

Upvotes: 2

Views: 5904

Answers (1)

dhartwich
dhartwich

Reputation: 398

def create
            name = params[:name]
            description = params[:description]
            orga = params[:raidlead]
            startdate = params[:startdate]
            enddate = params[:enddate]

            puts description

            name.force_encoding("ISO-8859-1").encode("UTF-8")
            description.force_encoding("ISO-8859-1").encode("UTF-8")
            orga.force_encoding("ISO-8859-1").encode("UTF-8")

Did the trick, so formatting the fields before saving them in the database did the trick for me. The method that does the trick is:

string.force_encoding("ISO-8859-1").encode("UTF-8")

Thanks to Prakash Murthy for his hint.

Upvotes: 2

Related Questions