gpt4 book ai didi

json - 将 JSON 解码为 UUID 类型

转载 作者:IT王子 更新时间:2023-10-29 01:24:47 26 4
gpt4 key购买 nike

我正在尝试使用 json.Unmarshaler 接口(interface)将 UUID 解码为结构上的 uuid.UUID 字段。我创建了一个名为 myUUID 的自定义类型,一切正常,直到我尝试访问通常位于 uuid.UUID 上的方法。我该如何处理?我是 Go 的新手,所以我可能还没有完全理解自定义类型。

package main

import (
"encoding/json"
"errors"
"fmt"

"code.google.com/p/go-uuid/uuid"
)

var jsonstring = `
{
"uuid": "273b62ad-a99d-48be-8d80-ccc55ef688b4"
}
`

type myUUID uuid.UUID

type Data struct {
uuid myUUID
}

func (u *myUUID) UnmarshalJson(b []byte) error {
id := uuid.Parse(string(b[:]))
if id == nil {
return errors.New("Could not parse UUID")
}
*u = myUUID(id)
return nil
}

func main() {
d := new(Data)
err := json.Unmarshal([]byte(jsonstring), &d)
if err != nil {
fmt.Printf("%s", err)
}
fmt.Println(d.uuid.String())
}

最佳答案

您可能想确保您的 myuuid 变量在 Data struct 中可见/导出:如在“public”中一样。
类型别名 MyUUID 相同(而不是 myUUID)

type MyUUID uuid.UUID

type Data struct {
Uuid MyUUID
}

来自 JSON and Go :

The json package only accesses the exported fields of struct types (those that begin with an uppercase letter).


作为commented通过 Ainar G , style guide还推荐:

Words in names that are initialisms or acronyms (e.g. "URL" or "NATO") have a consistent case.
For example, "URL" should appear as "URL" or "url" (as in "urlPony", or "URLPony"), never as "Url". Here's an example: ServeHTTP not ServeHttp.

This rule also applies to "ID" when it is short for "identifier," so write "appID" instead of "appId".

在您的情况下,这意味着:

type Data struct {
UUID MyUUID
}

关于json - 将 JSON 解码为 UUID 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25258439/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com