解码具有多个带有分隔标签的构造器的对象 [英] Decoding object with multiple constuctors with separated tags

查看:69
本文介绍了解码具有多个带有分隔标签的构造器的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有成对的两个字符串形式的数据,其中第一个是识别作为第二个JSON传递的JSON形状的密钥.

I have data in form of pairs of two strings, where first is the key identifying shape of the JSON delivered as the second one.

fooooo
{"a": 123}

barrrr
{"a": 123, "b": 123}

fooooo
{"a": 123}

我想将其解析为相同的数据类型,基于fopooobaasdasda1:

I would like to parse it to same data type, based on the fopooo, baasdasda1, etc :

data Test
  = Foo
    { a :: Int
    , b :: Int
    }
  | Bar
    { a :: Int
    }
  deriving (Show, Generic)

在Aeson中有一个标签功能,但是它似乎需要在对象内部存在标签.

In the Aeson there is a tag feature, but it seems to require presence of the tag inside the object.

是否有某种处理方式(带有外部标签)

magicDecode :: String -> Test
magicDecode "fooooo" = decodeSpecyfic Foo
magicDecode "barrrr" = decodeSpecyfic Bar

还是类似的东西?

我为此屈从于处理带有记录的类型

I've currenlty mananged to handle types with records by this

test :: [(String, Text)]
test =
  [ ("foooo", "Foo")
  , ("barrr", "Bar")
  , ("aaaa", "Lel")
  ]

dec :: String -> ByteString -> Test
dec t x =
  fromJust $
  parseMaybe
    (genericParseJSON defaultOptions {sumEncoding = ObjectWithSingleField})
    (object [fromJust (lookup t test) .= fromJust (decode x :: Maybe Value)])

(问题是如果您不是构造函数参数:()

(Issue is if thee are no constructor params :( )

推荐答案

您可以使用UntaggedValue选项:

{-# LANGUAGE DeriveGeneric #-}
module Q59916344 where

import Data.Aeson
import GHC.Generics

myOptions = defaultOptions { sumEncoding = UntaggedValue }

data Test = Foo { a :: Int, b :: Int } | Bar { a :: Int } deriving (Show, Generic)

instance FromJSON Test where
  parseJSON = genericParseJSON myOptions

instance ToJSON Test where
  toJSON     = genericToJSON myOptions
  toEncoding = genericToEncoding myOptions

文档解释了有关UntaggedValue的信息:

As the documentation explains about UntaggedValue:

解码时,按定义顺序尝试构造函数.如果某些编码重叠,则定义的第一个编码将成功.

When decoding, constructors are tried in the order of definition. If some encodings overlap, the first one defined will succeed.

演示:

*Q59916344 Q59916344> decode "{\"a\": 123}" :: Maybe Test
Just (Bar {a = 123})
*Q59916344 Q59916344> decode "{\"a\": 123, \"b\": 123}" :: Maybe Test
Just (Foo {a = 123, b = 123})

也就是说,您不应该使用记录来建模求和类型,因为记录访问器是部分访问的:

That said, you shouldn't model sum types with records, because the record accessors are partial:

*Q59916344 Q59916344> b (Foo 42 1337)
1337
*Q59916344 Q59916344> b (Bar 42)
*** Exception: No match in record selector b

这篇关于解码具有多个带有分隔标签的构造器的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆