Ruby to_json для объектов, заключенных в цитату

Я пытаюсь создать очень простой веб-сервис JSON для побочного проекта. Однако у меня возникли проблемы с преобразованием моих объектов в JSON, не мог бы кто-нибудь мне помочь?

У меня есть следующие классы:

class Location
  attr_reader :street, :city, :state, :country, :zip, :latitude, :longitude

  def initialize(street, city, state, country, zip, latitude, longitude)
    @street = street
    @city = city
    @state = state
    @country = country
    @zip = zip
    @latitude = latitude
    @longitude = longitude
  end

  def to_json
    {
      'street' => @street,
      'city' => @city,
      'state' => @state,
      'country' => @country,
      'zip' => @zip,
      'latitude' => Float(@latitude),
      'longitude' => Float(@longitude)
    }.to_json
  end
end

и

class Spot
  attr_reader :name, :category, :location, :id

  def initialize(id, name, category, location)
    @name = name
    @category = category
    @location = location
    @id = id
  end

  def to_json
    {
      'name' => @name,
      'category' => @category,
      'location' => @location.to_json,
      'id' => @id
    }.to_json
  end

end

Учитывая случайный ввод, я бы хотел, чтобы результат был примерно таким :

{
"name":"Wirelab",
"category":"Bier",
"location":
{
    "street":"Blaatstraat 12",
    "city":"Enschede",
    "state":"Overijssel",
    "country":"Nederland",
    "zip":"7542AB",
    "latitude": 31.21312,
    "longitude":41.1209
}
,
"id":"12"
}

Однако вывод, который я получу, такой:

{
    "name":"Wirelab",
    "category":"Bier",
    "location":"
    {
        "street\":"Blaatstraat 12",
        "city\":\"Enschede\",
        \"state\":\"Overijssel\",
        \"country\":\"Nederland\",
        \"zip\":\"7542AB\",
        \"latitude\":31.21312,
        \"longitude\":41.1209
    }
    ",
    "id":"12"
}

Не могли бы вы объяснить мне, как я могу это исправить?

РЕДАКТИРОВАТЬ:

Я использую веб-сервис Sintra, который выглядит примерно так:

get '/spots' do  
       #json = spots.to_json
       spot =  Spot.new("12", "Wirelab", "Bier", Location.new("Blaatstraat 12", "Enschede", "Overijssel", "Nederland", "7542AB", "31.21312", "41.1209"))
       json = spot.to_json
       if callback
         content_type :js
         response = "#{callback}(#{json})" 
      else
         content_type :json
         response = json
       end
  response
end
5
задан Gidogeek 2 May 2011 в 09:30
поделиться