2016-03-08 138 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