简体   繁体   English

实例Data.Sequence与Haskell Aeson

[英]Instance Data.Sequence with Haskell Aeson

I have the next problem with Data.Sequence and Aeson. 我有Data.Sequence和Aeson的下一个问题。 I want to create my data DraftVar deriving Generic , which use Data.Sequence on the constructor DV2 . 我想创建我的数据DraftVar派生Generic ,它在构造函数DV2上使用Data.Sequence

{-# LANGUAGE DeriveGeneric, OverloadedStrings #-}

-- Imports

import Data.Aeson
import GHC.Generics

import qualified Data.Sequence as DS

-- Data

data DraftVar = 
    DV1 { dv1_val :: Int }
    | DV2 { dv2_list :: DS.Seq DraftVar }
    deriving (Show, Generic)

instance ToJSON DraftVar
instance FromJSON DraftVar

With this code, I receive and error that says: No instance for (ToJSON (DS.Seq DraftVar)) . 使用此代码,我收到并显示错误: No instance for (ToJSON (DS.Seq DraftVar)) So I need to create a instance of Data.Sequence for the Aeson library. 所以我需要为Aeson库创建一个Data.Sequence实例。

On the ToJSON instance declaration, I decide to transform the Data.Sequence to a list. ToJSON实例声明中,我决定将Data.Sequence转换为列表。 The code is: 代码是:

import Data.Foldable as DF

instance (Show a) => ToJSON (DS.Seq a) where
    toJSON l = object [ "values" .=  show (DF.toList l) ]

But what happen, when I want to extract from this Json the list and then transform the data to Data.Sequence ? 但是,当我想从这个Json中提取列表然后将数据转换为Data.Sequence什么?

instance (Show a) => FromJSON (DS.Seq a) where
    parseJSON (Object o) = ???

Maybe I need a library or an special function from Aeson, I don't know. 也许我需要Aeson的图书馆或特殊功能,我不知道。 The most useful example (that I found) is this: Parsing an Array with Haskell Aeson 最有用的例子(我发现)是这样的: 用Haskell Aeson解析一个数组

Do you have a better approach? 你有更好的方法吗?

[] and Seq are isomorphic via fromList / toList (they just have vastly different representations and performance characteristics), so the most straightforward way to implement FromJSON and ToJSON for Seq is by re-using the existing implementation for [] : []Seq通过fromList / toList是同构的(它们只有很多不同的表示和性能特征),所以为Seq实现FromJSONToJSON最直接的方法是重用[]的现有实现:

import qualified Data.Sequence as DS
import Data.Foldable as DF

instance (ToJSON a) => ToJSON (DS.Seq a) where
    toJSON = toJSON . DF.toList

instance (FromJSON a) => FromJSON (DS.Seq a) where
    parseJSON = fmap DS.fromList . parseJSON

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM