如何配置JSON.mapping让Array of Strings Array成为Hash?

How to configure JSON.mapping for Array of Array of Strings to become a Hash?

我正在尝试处理从 API.

收到的以下 JSON
{"product":"midprice",
"prices":[
  ["APPLE","217.88"],
  ["GOOGLE","1156.05"],
  ["FACEBOOK","160.58"]
]}

我可以获得一个基本映射:

require "json"

message = "{\"product\":\"midprice\",\"prices\":[[\"APPLE\",\"217.88\"],[\"GOOGLE\",\"1156.05\"],[\"FACEBOOK\",\"160.58\"]]}"

class Midprice
  JSON.mapping(
    product: String,
    prices: Array(Array(String)),
  )
end

midprice = Midprice.from_json(message)
p midprice.product # Outputs the String
p midprice.prices # Outputs 

Crystal 0.26.1 代码:https://play.crystal-lang.org/#/r/515o

但理想情况下,我希望价格是一个散列,其中股票名称为键,价格为值。这可以用 JSON.mapping 来完成吗?

JSON.mapping 将被删除,取而代之的是 JSON::Serializable 和注释。您可以像这样使用它:

class Midprice
  include JSON::Serializable

  getter product : String

  @[JSON::Field(converter: StockConverter.new)]
  getter prices : Hash(String, String)
end

您需要使用converterprices修改为您想要的格式。

在这种情况下,输入是 Array(Array(String)),输出是不同类型的 Hash(String, String)。您需要为转换器实现自定义 from_json 方法。

class StockConverter
  def initialize
    @prices = Hash(String, String).new
  end

  def from_json(pull : JSON::PullParser)
    pull.read_array do
      pull.read_array do
        stock = pull.read_string
        price = pull.read_string

        @prices[stock] = price
      end
    end

    @prices
  end
end

这是完整的工作代码:https://play.crystal-lang.org/#/r/51d9