2016-03-08 101 views
0

我正在做TodoList,而 想将列表保存为JSON文件,但它只保存了Class名称。将数组中的类转换为JSON

下面的代码:

require 'date' 
require 'json' 
class TodoList 
    attr_accessor :title 

    def initialize(title) 
     @title=title 
     @items=[] 
    end 

    def rename(title) 
     @title=title 
    end 

    def add_item(new_item, due_date) 
     item=Item.new(new_item) 
     item.set_due_date(due_date)     
     @items.push(item) 
    end 

    def save 
     if json_instance = self.to_json 
      puts "Saved Successfully" 
     end 

     File.open("file_json_complete.json", "w") do |f| 
      f.write(json_instance) 
     end 
    end 
end 

class Item 
    attr_reader :complete_status, :description, :due_date, :created_at  

    def initialize(description) 
     @description=description 
     @complete_status=false 
     @created_at=Date.today 
    end 
end 

doh=TodoList.new("doh's stuff") 
# Add four new items 
doh.add_item("laundry", 10) 
doh.add_item("study",20) 
doh.add_item("sleep", 15) 
doh.add_item("Watch Movie", 5) 
doh.save 

结果文件中只显示类名TodoList:0x00000000965e88

回答

0

要做到这一点适当的我会建议增加以下内容:

class TodoList 
    def to_json(options={}) 
    {title: @title, items: @items}.to_json(options) 
    end 
end 

class Item 
    def to_json(options={}) 
    {description: @description, completed: @complete_status, 
     created: @created_at, due: @due_date}.to_json(options) 
    end 
end 

然后当你调用to_jsonTodoList你会得到类似的东西:

"{\"title\":\"doh's stuff\", 
    \"items\":[ 
     {\"description\":\"laundry\",\"complete\":false,\"created\":\"2016-03-08\",\"due\":\"2017-01-08\"}, 
     {\"description\":\"study\",\"complete\":false,\"created\":\"2016-03-08\",\"due\":\"2017-11-08\"}, 
     {\"description\":\"sleep\",\"complete\":false,\"created\":\"2016-03-08\",\"due\":\"2017-06-08\"}, 
     {\"description\":\"Watch Movie\",\"complete\":false,\"created\":\"2016-03-08\",\"due\":\"2016-08-08\"} 
    ] 
}" 

我正在设想的是你在找什么。

基本上to_json将递归调用的嵌套对象to_json创建结构,这将最终违约,当你还没有实现一个to_json方法to_s方法。

+1

谢谢。这一个正是我想要的.. –

0

您正在保存TodoList类的当前实例。
您必须保存您的@items变量。要做到这一点,你必须改变self.to_json@items.to_json

0
class TodoList 

    ... 

    def save 
    File.open("file_json_complete.json", "w") do |f| 
     f.write(@items.to_json) 
    end 
    puts "Saved Successfully" 
    end 

    ... 

end