我正在尝试处理从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来完成吗?
发布于 2018-09-18 23:07:03
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
下面是完整的工作代码:https://play.crystal-lang.org/#/r/51d9
https://stackoverflow.com/questions/52377857
复制相似问题