在 Haskell 中使用 Aeson 编码代数数据类型

问题描述

我有以下 ADT 实现:

data FeatureValue =
    FvInt Int
  | FvFloat Float
  | FvText Text
  | FvBool Bool
  deriving Show

data ApiResponse =
    Online [[Maybe FeatureValue]]
  | Offline [[[Maybe FeatureValue]]]
  deriving Show

要编码的示例值可能是:

example :: ApiResponse
example =
    Online [
        [Just (FvInt 10),Nothing,Just (FvText "foo"),Just (FvFloat 1.42)],[Nothing,Just (FvBool False),Just (FvText "bar"),Nothing]
    ]

这将导致以下 JSON:

[
    [10,null,"foo",1.42],[null,false,"bar",null]
]

我正在努力研究如何在 ToJSON 上派生 FeatureValue 实例。使用 Aeson 进行 ADT 编码的文档特别稀少(例如,以 a glorious "Summary: TODO" for the section concerning ADT encoding/decoding 为特色的其他出色的 Aelve 指南)。

解决方法

the documentation 开始,我们只需要提供一个 FeatureValue -> Value 类型的函数。 Value 的定义也被记录并完全导出。所以就跟着你的鼻子走。

instance ToJSON FeatureValue where
    toJSON (FvInt n) = Number (fromIntegral n)
    toJSON (FvFloat f) = Number (realToFrac f)
    toJSON (FvText t) = String t
    toJSON (FvBool b) = Bool b

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...