Aeson Haskell-没有(ToJSON ByteString)的实例 [英] Haskell, Aeson - no instance for (ToJSON ByteString)

查看:53
本文介绍了Aeson Haskell-没有(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:

为了修复它,我将其转换为 Text 类型,然后编码为JSON.

For fixing it, I would convert it to Text type and then encode into JSON.

这篇关于Aeson Haskell-没有(ToJSON ByteString)的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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