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

Encoding Algebraic Data Types with Aeson in Haskell

我有以下 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]
]

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

From the documentation, we simply need to provide a function of type FeatureValue -> Value. The definition of 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