2011-12-02 109 views
1

我有一個iPhone應用程序 的rubyonrails後端的Web服務以JSON格式如何將以json格式接收的數據保存到數據庫中?

如接收數據:

[ 
{"created_at":"2011-11-28T12:53:25Z","body":"good article","updated_at":"2011-11-23T12:53:30Z","id":1,"commenter":"shanib","user_id":1}, 
{"created_at":"2011-11-28T07:29:53Z","body":"dfasdf","updated_at":"2011-11-28T07:29:53Z","id":2,"commenter":"dasf","user_id":1}, 
{"created_at":"2011-11-28T08:36:37Z","body":"","updated_at":"2011-11-28T08:36:37Z","id":3,"commenter":"","user_id":1}, 
{"created_at":"2011-11-28T12:41:18Z","body":"qwewqe","updated_at":"2011-11-28T12:41:18Z","id":4,"commenter":"Allen","user_id":1} 
] 

如何可以解析此JSON和使用循環

保存到數據庫中你能提供任何參考鏈接或演示?

+0

你需要序列化,然後將其插入到數據庫中。 – Anil

+0

你能告訴我一個例子嗎? – Shanib

+0

如果你有一個具有匹配屬性/列的模型/表格,請問如何序列化它?這裏有一個類似的問題,應該有所幫助:http://stackoverflow.com/questions/1826727/how-do-i-parse-json-with-ruby-on-rails –

回答

1

您可以使用'json'寶石。 (現在已經與rails 3.1.x一起安裝)。

例如:

json_data = '[ 
{"created_at":"2011-11-28T12:53:25Z","body":"good article","updated_at":"2011-11-23T12:53:30Z","id":1,"commenter":"shanib","user_id":1}, 
{"created_at":"2011-11-28T07:29:53Z","body":"dfasdf","updated_at":"2011-11-28T07:29:53Z","id":2,"commenter":"dasf","user_id":1}, 
{"created_at":"2011-11-28T08:36:37Z","body":"","updated_at":"2011-11-28T08:36:37Z","id":3,"commenter":"","user_id":1}, 
{"created_at":"2011-11-28T12:41:18Z","body":"qwewqe","updated_at":"2011-11-28T12:41:18Z","id":4,"commenter":"Allen","user_id":1} 
]' 

data = JSON.parse(data) 

會給你一個哈希,你可以遍歷低谷。 (你可以使用類似數據[0] [「created_at」])來訪問這些值。

相關問題