如何指定JSON值的类型?

时间:2016-01-12 14:30:34

标签: ruby json api

我在Padrino上使用Grape为我的移动应用程序制作测试API。

如何指定JSON对象的类型?

我是这样做的,但每个返回的值都是一个字符串:

module Acme
  module Api
    class Ping < Grape::API
      format :json

       get '/user/112132a08s245c/availability_list' do
            {
                "availability_list"=> [
              {
                :type=> "OOO",
                :from_date=> "21-12-2004",
                :to_date=> "21-23-2007",
                :all_day=> "false"

                },
              {
                :type=> "WFH",
                :from_date=> "21-12-2004",
                :to_date=> "21-23-2007",
                :all_day=> "false"
                }

              ]
      }
      end


       get '/user/112132a08s245c/issues' do
            {
                "issues"=> [
              {
                :issure_id=> "1ab300co221",
                :title=> "No water",
                :description=> "No water in kitchen",
                :severity=> "low",
                "location" => {
                  :lat => "37.4224764",
                  :lng => "-122.0842499"
                }

                },
              {
                :issure_id=> "1ab300co222",
                :title=> "No fire",
                :description=> "No fire in kitchen",
                :severity=> "low",
                "location" => {
                  :lat => "37.4224764",
                  :lng => "-122.0842499"
                }

                }

              ]
      }
      end

    end
  end

1 个答案:

答案 0 :(得分:1)

默想:

require 'json'

foo = {'a' => 1}
foo.class # => Hash
str = JSON[foo] # => "{\"a\":1}"
str.class # => String
bar = JSON[str] # => {"a"=>1}
bar.class # => Hash

您需要阅读the JSON spec。 JSON将数据序列化为字符串,因为对象无法在不同的语言之间传输。当它看到一个对象时,解析器将它序列化为一个字符串。当传入的字符串被接收并传递给解析器时,它知道它必须将字符串转换回对象。