Aeson Haskell-没有(ToJSON ByteString)的实例 [英] Haskell, Aeson - no instance for (ToJSON ByteString)
问题描述
很高兴到目前为止,遇到了一个新的障碍:将此代码编码为JSON.但是,无论何时将类型用作实例,编译器都会抱怨.现在,我显然做错了什么,但这恰恰是文档中的内容(显然是在使用DeriveGeneric时).
So happy making it this far, encountered a new hurdle: Got this code made to be encoded to JSON. However no matter when type I use as an instance, the compiler complains. Now I am obviously doing something wrong, but it is exactly what is in the documentation (when using DeriveGeneric obviously).
{-# LANGUAGE OverloadedStrings, DeriveGeneric #-}
import Data.Aeson
import Data.Text as T
import Data.ByteString.Lazy as B
import Data.ByteString.Lazy.Char8 as BC
import GHC.Generics
-- decode :: FromJSON a => B.ByteString -> Maybe a
-- decode' :: FromJSON a => B.ByteString -> Either String a
-- encode :: ToJSON => a -> B.ByteString
data System = System { system :: BC.ByteString
, make :: BC.ByteString
, code :: Int
} deriving (Generic, Show)
instance ToJSON System
-- instance FromJSON System
platform = System { system = "FPGA"
, make = "Xilinx"
, code = 10165
}
encodePlatform :: BC.ByteString
encodePlatform = encode platform
编译器输出:
• No instance for (ToJSON ByteString)
arising from a use of ‘aeson-1.4.1.0:Data.Aeson.Types.ToJSON.$dmtoJSON’
• In the expression:
aeson-1.4.1.0:Data.Aeson.Types.ToJSON.$dmtoJSON @(System)
In an equation for ‘toJSON’:
toJSON = aeson-1.4.1.0:Data.Aeson.Types.ToJSON.$dmtoJSON @(System)
In the instance declaration for ‘ToJSON System’
|
17 | instance ToJSON System
推荐答案
这是因为对于 ToJSON
类型类,没有 ByteString
实例.从历史上看,它曾经存在过,但由于JSON字符串应为有效的Unicode而被删除.
That's because there is no ByteString
instance for ToJSON
typeclass. Historically, it used to be present but it was removed because JSON strings should be valid unicode.
您可以在此处找到更多详细信息:
You can find more details here:
- https://github.com/bos/aeson/issues/126
- https://github.com/bos/aeson/commit/9ee73f303cacb8ae73b2325f2f47288522607420
- https://github.com/bos/aeson/pull/148/files
为了修复它,我将其转换为 Text
类型,然后编码为JSON.
For fixing it, I would convert it to Text
type and then encode into JSON.
这篇关于Aeson Haskell-没有(ToJSON ByteString)的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!