首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将字符串数组的JSON.mapping配置为哈希?

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

Stack Overflow用户
提问于 2018-09-18 09:59:03
回答 1查看 379关注 0票数 3

我正在尝试处理从API收到的以下JSON。

代码语言:javascript
复制
{"product":"midprice",
"prices":[
  ["APPLE","217.88"],
  ["GOOGLE","1156.05"],
  ["FACEBOOK","160.58"]
]}

我可以使用以下命令获得基本的映射:

代码语言:javascript
复制
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来完成吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-09-18 23:07:03

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

代码语言:javascript
复制
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方法。

代码语言:javascript
复制
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

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52377857

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档