evolve75/RubyTree

NoMethodError: undefined method `name' for "children":String when creating from JSON

Closed this issue · 1 comments

I have created a tree as by the example in the README:

require 'tree'
require 'JSON'
root_node = Tree::TreeNode.new("ROOT", "Root Content")
root_node << Tree::TreeNode.new("CHILD1", "Child1 Content") << Tree::TreeNode.new("GRANDCHILD1", "GrandChild1 Content")
root_node << Tree::TreeNode.new("CHILD2", "Child2 Content")

I then create a JSON string from this tree:

j = root_node.to_json
=> {"name":"ROOT","json_class":"Tree::TreeNode","content":"Root Content","children":[{"name":"CHILD1","json_class":"Tree::TreeNode","content":"Child1 Content","children":[{"name":"GRANDCHILD1","json_class":"Tree::TreeNode","content":"GrandChild1 Content"}]},{"name":"CHILD2","json_class":"Tree::TreeNode","content":"Child2 Content"}]}

Then I want to create a new tree from the generated JSON:

other_node = Tree::TreeNode.json_create(j)

However, this results in an exception:

NoMethodError: undefined method `name' for "children":String
from /Users/ariejan/.rvm/gems/ruby-1.8.7-p249/gems/rubytree-0.7.0/lib/tree.rb:242:in `add'
from /Users/ariejan/.rvm/gems/ruby-1.8.7-p249/gems/rubytree-0.7.0/lib/tree.rb:219:in `<<'
from /Users/ariejan/.rvm/gems/ruby-1.8.7-p249/gems/rubytree-0.7.0/lib/tree.rb:756:in `json_create'
from /Users/ariejan/.rvm/gems/ruby-1.8.7-p249/gems/rubytree-0.7.0/lib/tree.rb:755:in `each'
from /Users/ariejan/.rvm/gems/ruby-1.8.7-p249/gems/rubytree-0.7.0/lib/tree.rb:755:in `json_create'

Hi,

You should not invoke Tree::TreeNode.json_create directly. Instead, do:

other_node = JSON.parse(j)

This will return the correct results. See http://flori.github.com/json/doc/index.html for more details.

I will update the documentation to make this more clear.