我正在尝试为侧面项目创建一个超级简单的JSON Web服务.但是我在将对象转换为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
Run Code Online (Sandbox Code Playgroud)
和
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
Run Code Online (Sandbox Code Playgroud)
给定一个随机输入我希望输出是这样的:
{
"name":"Wirelab",
"category":"Bier",
"location":
{
"street":"Blaatstraat 12",
"city":"Enschede",
"state":"Overijssel",
"country":"Nederland",
"zip":"7542AB",
"latitude": 31.21312,
"longitude":41.1209
}
,
"id":"12"
}
Run Code Online (Sandbox Code Playgroud)
但是我得到的输出是这样的:
{
"name":"Wirelab",
"category":"Bier",
"location":"
{
"street\":"Blaatstraat 12",
"city\":\"Enschede\",
\"state\":\"Overijssel\",
\"country\":\"Nederland\",
\"zip\":\"7542AB\",
\"latitude\":31.21312,
\"longitude\":41.1209
}
",
"id":"12"
}
Run Code Online (Sandbox Code Playgroud)
有人可以解释一下我如何解决这个问题吗?
编辑:
我正在使用Sintra webservice,它看起来像这样:
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
Run Code Online (Sandbox Code Playgroud)
这应该可以修复它:
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_hash
{
'street' => @street,
'city' => @city,
'state' => @state,
'country' => @country,
'zip' => @zip,
'latitude' => Float(@latitude),
'longitude' => Float(@longitude)
}
end
def to_json
self.to_hash.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_hash
{
'name' => @name,
'category' => @category,
'location' => @location.to_hash,
'id' => @id
}
end
def to_json
self.to_hash.to_json
end
end
Run Code Online (Sandbox Code Playgroud)
您的问题是,在 Spot 的 to_json 中,您使用了 Location 的 json 字符串并将其编码为 json。这会导致 json 字符串中出现一个 json 字符串,这就是为什么有很多 '\' - 用作转义字符。
| 归档时间: |
|
| 查看次数: |
5823 次 |
| 最近记录: |