ROR中的JSON数组解析 [英] JSON Array parsing in ROR

查看:113
本文介绍了ROR中的JSON数组解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从Android应用程序中以以下格式获取JSON

I am getting JSON in following format from my Android application

{"list":[{"itemno":"w01","name":"t01","amount":"120","status":"done"},{"itemno":"w02","name":"t02","amount":"120","status":"done"},{"itemno":"w03","name":"t03,"amount":"120","status":"done""}]}

我需要对此进行解析以插入到mysql表"list"中.我在控制器中修改了创建"代码,如下所示:

I need to parse this to insert into mysql table "list". I modified "create" code in my controller as below

def create
lists = params[:list].collect{|key,list_attributes| List.new(list_attributes) }
    all_list_valid = true
    lists.each_with_index do |list,index|
     unless list.valid?
      all_list_valid = false
      invalid_list = lists[index]
     end
    end

    if all_list_valid
     @lists = []
     lists.each do |list|
       list.save
       @lists << list
     end
      format.html { redirect_to @list, notice: 'List was successfully created.' }
      format.json { render json: @list, status: :created, location: @list } 
    else
      format.html { render action: "new" }
      format.json { render json: @list.errors, status: :unprocessable_entity }
    end
  end

但是它无法解析JSON,因此不调用create方法.我对ROR非常陌生,并且也从Web尝试了上述代码.不知道上面的整个部分是不正确的还是我遗漏了一些东西.请指教.谢谢.

But its unable to parse the JSON, so not calling the create method. I am very new to ROR and tried above code too from web. Not sure if the entire piece above is incorrect or I am missing something. Please advise. Thanks.

推荐答案

此外,您可以对代码进行一些重构:

Also, you can refactor your code a little bit:

# This part of code
@lists = []
lists.each do |list|
  list.save
  @lists << list
end
# Can be shortened:
lists.map(&:save)
@lists = lists

整个动作可以像这样重构:

The whole action can be refactored like this:

def create
  lists = params[:list].each{ |list_attributes| List.new(list_attributes) }
  valid, not_valid = lists.partition{ |list| list.valid? }

  if not_valid.blank?
    lists.map(&:save)
    @lists = lists
    format.html { redirect_to @list, notice: 'List was successfully created.' }
    format.json { render json: @list, status: :created, location: @list }
  else
    format.html { render action: "new" }
    format.json { render json: @list.errors, status: :unprocessable_entity }
  end
end

这篇关于ROR中的JSON数组解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆