登录
首页 >  Golang >  Go问答

使用 Go 将调色板编码为 JSON 格式并解码回调色板

来源:stackoverflow

时间:2024-03-15 23:24:29 106浏览 收藏

在 Go 语言中,将自定义调色板(类型为 []color.Color)编码为 JSON 格式时会遇到困难,因为无法在解组时创建接口的具体类型。为了解决这个问题,建议使用 color.RGBA 类型,它可以方便地编码和解码。不过,如果您仍希望使用 color.Color 接口,可以通过实现自定义 unmarshaljson 函数,将解码后的数据转换为接口类型。这种方法涉及使用中间层将 JSON 数据解码为 color.RGBA 类型,然后将其转换为 color.Color 接口。

问题内容

我想在 json 文件中存储自定义调色板,但调色板的类型为 []color.color (这是一个接口,而不是具体类型)。当我整理调色板时,我得到如下内容:

[{"r":0,"g":0,"b":0,"a":255},{"r":0,"g":0,"b":51,"a":255}...]

问题是,当我解组 json 时,类型 []color.color 不起作用,因为 go 无法在该接口下创建具体类型。

我已将代码简化为以下示例:

type myT struct {
    P []color.Color
}

func main() {
    t := myT{palette.WebSafe}
    b, err := json.Marshal(t)
    e("json.Marshal", err)
    t2 := myT{}
    err = json.Unmarshal(b, &t2)
    e("json.Unmarshal", err)
    fmt.Println(string(b))
}

func e(s string, err error) {
    if err != nil {
        fmt.Println(s, err)
    }
}

https://play.golang.org/p/qyipj7l1ete

有一个简单的解决方案还是我必须将 []color.color 转换为 []color.rgba


解决方案


我会遵循 tim 的建议并开始使用 color.rgba,但如果您对如何为自定义类型实现自定义 unmarshaljson 函数感兴趣,我在下面概述了代码:https://play.golang.org/p/8p5a09993GV

基本上,您使用 unmarshaljson 函数作为中间层来解码为“正确的”rgba 类型,然后进行一些类型转换以使其成为您自定义 myt 类型上所需的接口。

同样,在整体实现中使用 color.rgba 而不是 color.color 可能更容易,但如果您愿意,这就是您可以转换它的方式。

这是一个涉及基础知识的好要点: https://gist.github.com/mdwhatcott/8dd2eef0042f7f1c0cd8

gopher 学院的一篇博客文章确实做了一些有趣的事情: https://blog.gopheracademy.com/advent-2016/advanced-encoding-decoding/

关于为什么 []struct 与它可能实现的 []interface 不 1/1 匹配的一个很好的解释: golang: slice of struct != slice of interface it implements?

package main

import (
    "encoding/json"
    "fmt"
    "image/color"
    "image/color/palette"
)

type myT struct {
    P []color.Color
}

func main() {
    t := myT{palette.WebSafe}
    b, err := json.Marshal(t)
    e("json.Marshal", err)
    t2 := myT{}
    err = json.Unmarshal(b, &t2)
    e("json.Unmarshal", err)
    fmt.Println(string(b))
    fmt.Println(string(t2))
}

func e(s string, err error) {
    if err != nil {
        fmt.Println(s, err)
    }
}

func (myt *myT) UnmarshalJSON(b []byte) error {
    var tempJson struct {
        P []color.RGBA
    }
    // Unmarshal to our temp struct
    err := json.Unmarshal(b, &tempJson)
    if err != nil {
        return err
    }
    // convert our new friends O(n) to the interface type
    newColors := make([]color.Color, len(tempJson.P))
    for i, v := range tempJson.P {
        newColors[i] = color.Color(v)
    }
    myt.P = newColors
    return nil
}

到这里,我们也就讲完了《使用 Go 将调色板编码为 JSON 格式并解码回调色板》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>