【发布时间】:2015-08-02 01:43:50
【问题描述】:
我有一个 Person 类,它定义了一个 to_json 方法:
class Person
...
def to_json
{
last_name: @last_name,
first_name: @first_name,
gender: @gender,
favorite_color: @favorite_color,
date_of_birth: @date_of_birth
}.to_json
end
end
在另一个类中,我正在处理一组Person 对象。如何将此数组作为一长段有效 JSON 数据返回?我尝试在这个新类中定义to_json,如下所示:
class Directory
...
def to_json
@people.map do |person|
person.to_json
end.to_json
end
end
但这给了我一些看起来很奇怪的东西,一堆 " 和 \ 字符散布在 JSON 数据中,如下所示:
["{\"last_name\":\"Dole\",\"first_name\":\"Bob\",\"gender\":\"M\",\"favorite_color\":\"Red\",\"date_of_birth\":\"01/02/1950\"}","{\"last_name\":\"Man\",\"first_name\":\"Bean\",\"gender\":\"M\",\"favorite_color\":\"Blue\",\"date_of_birth\":\"04/03/1951\"}","{\"last_name\":\"Man\",\"first_name\":\"Green\",\"gender\":\"F\",\"favorite_color\":\"Yellow\",\"date_of_birth\":\"02/15/1955\"}","{\"last_name\":\"Clinton\",\"first_name\":\"Bill\",\"gender\":\"M\",\"favorite_color\":\"Orange\",\"date_of_birth\":\"02/23/1960\"}"]
而在Person 上调用to_json 的格式很好:
{"last_name":"Bob","first_name":"Hob","gender":"M","favorite_color":"red","date_of_birth":"01/01/2000"}
【问题讨论】: