Arrays 在Ruby中将对象数组转换为JSON
我有一个Arrays 在Ruby中将对象数组转换为JSON,arrays,ruby,json,Arrays,Ruby,Json,我有一个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 en
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数据的长块返回?我试着在这个新类中定义到_json
,如下所示:
class Directory
...
def to_json
@people.map do |person|
person.to_json
end.to_json
end
end
但这给了我一些奇怪的东西,在JSON数据中散布了一堆“
和\
字符,如下所示:
(代码)收集到的一部分。目前,该项代码的主要部分是以下几码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码。码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码名字“:”绿色“,”性别“:”F“,”最喜欢的颜色““黄色”、“出生日期”、“1955年2月15日”、“姓氏”、“克林顿”、“名字”、“比尔”、“性别”、“M”、“最喜欢的颜色”、“橙色”、“出生日期”、“1960年2月23日”]
而在一个Person
上调用到_json
的格式很好:
{“姓氏”:“Bob”,“名字”:“Hob”,“性别”:“M”,“最喜欢的颜色”:“红色”,“出生日期”:“01/01/2000”}
代码正在转换字符串数组(json字符串),而不是哈希数组
在目录#to#json
中使用Person#to#json
,而不是使用Person#to#hash
,如下所示:
class Person
def to_hash
{
last_name: @last_name,
first_name: @first_name,
gender: @gender,
favorite_color: @favorite_color,
date_of_birth: @date_of_birth
}
end
def to_json
to_hash.to_json
end
end
class Directory
def to_json
@people.map do |person|
person.to_hash
end.to_json
end
end