【发布时间】:2013-07-03 12:39:31
【问题描述】:
我可以使用以下代码解析 JSON
$httpresult = @params['body']
$jsonresult = Rho::JSON.parse($httpresult)
但我不知道如何从$jsonresult 创建模型。
【问题讨论】:
标签: ruby json rhomobile rhodes
我可以使用以下代码解析 JSON
$httpresult = @params['body']
$jsonresult = Rho::JSON.parse($httpresult)
但我不知道如何从$jsonresult 创建模型。
【问题讨论】:
标签: ruby json rhomobile rhodes
首先,使用app_info,您可以打印来自服务器的结果,以检查响应是否为有效的 JSON 字符串。
其次,我认为您必须解码 url 才能使用以下方法解析它:
Rho::JSON.parse(Rho::RhoSupport.url_decode(@params['body']))
【讨论】:
在 json_result 中获得数据后,您可以将它们放入预先存在的模型中。 假设您已经创建了一个名为“Product”的模型,您可以使用事务来加快流程。
在模块的开头,您必须要求模型名称:
require_source 'Product'
那么你就可以做这个回调了:
def get_callback
if @params['status'] == "ok"
json_result = Rho::JSON.parse(@params['body'])
db = ::Rho::RHO.get_src_db('Product')
db.start_transaction
Product.delete_all
begin
json_result.each do |item|
Product.create({:Brand => item["B rand"], :Name => item["Name"], :SKU => d["SKU"]})
end
db.commit
rescue Exception => e
trace_msg = e.backtrace.join("\n")
puts 'Application initialize failed: ' + e.inspect + ";Trace: #{trace_msg}"
db.rollback
end
WebView.navigate Rho::RhoConfig.start_path
else
WebView.navigate url_for :action => :show_error
end
end
【讨论】: