Haskell, Aeson之(ToJSON ByteString) 没有实例

zhengyun_ustc 阅读:63 2025-06-02 22:19:02 评论:0

很高兴能走到这一步,遇到了一个新的障碍:
将此代码编码为 JSON。但是,无论我何时使用类型作为实例,编译器都会提示。现在我显然做错了,但这正是文档中的内容(显然使用 DeriveGeneric 时)。

{-# 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 

请您参考如下方法:

那是因为没有ByteString ToJSON 的实例类型类。从历史上看,它曾经存在,但由于 JSON 字符串应该是有效的 unicode 而被删除。

您可以在此处找到更多详细信息:

  • https://github.com/bos/aeson/issues/126
  • https://github.com/bos/aeson/commit/9ee73f303cacb8ae73b2325f2f47288522607420
  • https://github.com/bos/aeson/pull/148/files

  • 为了修复它,我会将其转换为 Text输入然后编码成 JSON。


    标签:json
    声明

    1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

    关注我们

    一个IT知识分享的公众号