4

I have the following problem, I have a JSON format with optional keys that I need to generate from my haskell code.

Lets make an example

{-# LANGUAGE DeriveGeneric #-}

import GHC.Generics
import Data.Aeson

data Person = {
    name :: String,
    shoeSize :: Maybe Int,
    favoriteColor :: Maybe String,
    favoriteFood :: Maybe StringC
} deriving (show, eq, generic)

instance ToJSON Person -- Generic instance

now, if I try encoding a Person without a shoesize I still get a key "shoeSize" set to null, what is the Aeson way of making keys optional in encoding

edit, example of an encode

encode $ Person "windwarrior" Nothing "green" Nothing

should result in

{"name":"windwarrior", "favoriteColor":"green"}
4

2 に答える 2

8

の代わりにインスタンスTemplateHaskellを派生させるために使用します。TH 関数はオプションで、which を持つオプションを使用します。ToJSONGenericOptionsomitNothingFields

于 2013-10-29T18:20:23.240 に答える