如何为字符串数组配置JSON.mapping成为哈希?

问题描述 投票:2回答:1

我正在尝试处理从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 

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

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

crystal-lang
1个回答
7
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.