Haskell Data.Decimal作为Aeson类型 [英] Haskell Data.Decimal as Aeson type
问题描述
是否可以解析 Data.Decimal 从JSON使用Aeson包吗?
假设我有以下JSON:
{
foo:5.231,
bar:smth
}
以下记录类型:
data test {foo :: Data。 Decimal
,bar :: String}派生类型
with
instance FromJSON测试
实例ToJSON测试
如果不是 Data.Decimal
值为foo,那么这将起作用。
据我所知,我需要手动创建 FromJSON
和 ToJSON
(用于转换回JSON) Data.Decimal的实例,因为它不是从Generic派生的。我该怎么做?
预先感谢。
我知道这是一个古老的线索,但可能有助于某人。这里是我如何将Decimal转换为/从json转换(我从一堆其他代码组装这些代码,我现在还没有源代码): instance A.ToJSON(DecimalRaw Integer)其中
- 也许这不是最好的,但它可以工作
toJSON d = A.toJSON $ show d
实例A.FromJSON(DecimalRaw Integer)其中
parseJSON = A.withTextDecimal(go。(read :: String - > [(DecimalRaw Integer,String)])T.unpack)
其中
去[(v,[])] =返回v
去(_:xs)=去xs
去_ =失败无法解析数字
Is it possible to parse a Data.Decimal from JSON using the Aeson package?
Suppose I have the following JSON:
{
"foo": 5.231,
"bar": "smth"
}
And the following record type:
data test { foo :: Data.Decimal
, bar :: String } deriving Generic
with
instance FromJSON test
instance ToJSON test
This would work, if it weren't for the Data.Decimal
value "foo".
From what I understand I would need to manually create a FromJSON
and ToJSON
(for converting back to JSON) instance of Data.Decimal, since it doesn't derive from Generic. How can I do that?
Thanks in advance.
I know this is an old thread, but might help someone. Here is how I am converting Decimal to/from json (I assembled this code from a bunch of other code which I don't have the source for now):
instance A.ToJSON (DecimalRaw Integer) where
-- maybe this is not the best, but it works
toJSON d = A.toJSON $ show d
instance A.FromJSON (DecimalRaw Integer) where
parseJSON = A.withText "Decimal" (go . (read :: String -> [(DecimalRaw Integer, String)]) . T.unpack)
where
go [(v, [])] = return v
go (_ : xs) = go xs
go _ = fail "Could not parse number"
这篇关于Haskell Data.Decimal作为Aeson类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!