本文介绍了将json解析为对象ruby的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我调查了不同的资源,但仍然对如何将json格式解析为自定义对象感到困惑

I looked into different resources and still get confused on how to parse a json format to a custom object, for example

class Resident
  attr_accessor :phone, :addr

  def initialize(phone, addr)
      @phone = phone
      @addr = addr
  end
end

和JSON文件

{
  "Resident": [
    {
      "phone": "12345",
      "addr":  "xxxxx"
    }, {
      "phone": "12345",
      "addr": "xxxxx"
    }, {
      "phone": "12345",
      "addr": "xxxxx"
    }
  ]
}

将json文件解析为3个常驻对象数组的正确方法是什么?

what's the correct way to parse the json file into a array of 3 Resident object?

推荐答案

以下代码更简单:

require 'json'

data = JSON.parse(json_data)
residents = data['Resident'].map { |rd| Resident.new(rd['phone'], rd['addr']) }

这篇关于将json解析为对象ruby的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 05:35