如何派生Data.Messagepack 1.0.0的实例 [英] How to derive instances of Data.Messagepack 1.0.0

查看:103
本文介绍了如何派生Data.Messagepack 1.0.0的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以前版本的 Data.Messagepack 0.7.2.5 支持通过模板Haskell导出实例。但是,当前版本(1.0.0)。 p>

因此,我想知道是否有另一种方法来自动派生MessagePack 1.0.0实例,可能使用 XDeriveGeneric

解决方案

作为权宜之计,看看 msgpack-aeson 消息包的目录 github repo:

https://github.com/msgpack/msgpack-haskell/tree/master/msgpack-aeson



你可以从你的数据值 - > aeson < - >消息包。不一定高效,但方便,因为您可以通过 DeriveGeneric 自动获取ToJSON和FromJSON。



示例代码: p>

  { - #LANGUAGE DeriveGeneric,OverloadedStrings# - } 

导入Data.MessagePack.Aeson
将合格的Data.MessagePack导入为MP
import GHC.Generics
import Data.Aeson

data Foo = Foo {_a :: Int,_b :: String}
派生(通用)

实例ToJSON Foo
实例FromJSON Foo

toMsgPack :: Foo - >也许MP.Object
toMsgPack = decode。编码

test = toMsgPack(Foo 3asd)


The previous version of Data.Messagepack, 0.7.2.5 supports deriving instances via Template Haskell. The current version (1.0.0), however, doesn't.

I was hence wondering if there is an alternative way to automatically derive MessagePack 1.0.0 instances, possibly using XDeriveGeneric?

解决方案

As a stop-gap measure, have a look at the msgpack-aeson directory of the message-pack github repo:

https://github.com/msgpack/msgpack-haskell/tree/master/msgpack-aeson

You could go from your data values <-> aeson <-> message-pack. Not necessarily efficient, but convenient since you can auto derive ToJSON and FromJSON with DeriveGeneric.

Example code:

{-# LANGUAGE DeriveGeneric, OverloadedStrings #-}

import Data.MessagePack.Aeson
import qualified Data.MessagePack as MP
import GHC.Generics
import Data.Aeson

data Foo = Foo { _a :: Int, _b :: String }
  deriving (Generic)

instance ToJSON Foo
instance FromJSON Foo

toMsgPack :: Foo  -> Maybe MP.Object
toMsgPack =   decode . encode

test = toMsgPack (Foo 3 "asd")

这篇关于如何派生Data.Messagepack 1.0.0的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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