我正在尝试处理从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完成吗?
答案 0 :(得分:7)
JSON.mapping
将被删除,取而代之的是JSON::Serializable
和注释。您可以像这样使用它:
class Midprice
include JSON::Serializable
getter product : String
@[JSON::Field(converter: StockConverter.new)]
getter prices : Hash(String, String)
end
您需要使用converter
来将prices
修改为所需的格式。
在这种情况下,输入是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