登录
首页 >  Golang >  Go问答

键为结构时造成Marshal/unMarshal问题

来源:stackoverflow

时间:2024-02-25 22:51:27 154浏览 收藏

大家好,我们又见面了啊~本文《键为结构时造成Marshal/unMarshal问题》的内容中将会涉及到等等。如果你正在学习Golang相关知识,欢迎关注我,以后会给大家带来更多Golang相关文章,希望我们能一起进步!下面就开始本文的正式内容~

问题内容

我定义了一个名为 student 的结构体和一个名为 score 的映射。 数据结构如下图:

type student struct {
    countryid int
    regionid  int
    name      string
}

stu := student{111, 222, "tom"}
score := make(map[student]int64)
score[stu] = 100

我正在使用 json.marshal 将分数编组为 json,但我无法使用 json.unmarshal 来解组此 json。下面是我的代码。我正在使用函数 getmarshableobject 将 struct student 转换为可整理的字符串。 谁能告诉我如何处理这个 json 以将其解组回地图分数。

package main

import (
    "encoding/json"
    "fmt"
    "os"
    "reflect"
)

type Student struct {
    CountryID int
    RegionID  int
    Name      string
}

func GetMarshableObject(src interface{}) interface{} {
    t := reflect.TypeOf(src)
    v := reflect.ValueOf(src)
    kind := t.Kind()
    var result reflect.Value
    switch kind {
    case reflect.Map:
        //Find the map layer count
        layer := 0
        cur := t.Elem()
        for reflect.Map == cur.Kind() {
            layer++
            cur = cur.Elem()
        }
        result = reflect.MakeMap(reflect.MapOf(reflect.TypeOf("a"), cur))
        for layer > 0 {
            result = reflect.MakeMap(reflect.MapOf(reflect.TypeOf("a"), result.Type()))
            layer--
        }
        keys := v.MapKeys()
        for _, k := range keys {
            value := reflect.ValueOf(GetMarshableObject(v.MapIndex(k).Interface()))
            if value.Type() != result.Type().Elem() {
                result = reflect.MakeMap(reflect.MapOf(reflect.TypeOf("a"), value.Type()))
            }
            result.SetMapIndex(reflect.ValueOf(fmt.Sprintf("%v", k)), reflect.ValueOf(GetMarshableObject(v.MapIndex(k).Interface())))
        }
    default:
        result = v
    }
    return result.Interface()
}

func main() {
    stu := Student{111, 222, "Tom"}
    score := make(map[Student]int64)
    score[stu] = 100

    b, err := json.Marshal(GetMarshableObject(score))
    if err != nil {
        fmt.Println("error:", err)
    }
    os.Stdout.Write(b) //{"{111 222 Tom}":100}

    scoreBak := make(map[Student]int64)
    if err = json.Unmarshal(b, &scoreBak); nil != err {
        fmt.Println("error: %v", err) // get error here: cannot unmarshal object into Go value of type map[main.Student]int64
    }
}

解决方案


来自docs

func (s Student) MarshalText() (text []byte, err error) {
    type noMethod Student
    return json.Marshal(noMethod(s))
}

func (s *Student) UnmarshalText(text []byte) error {
    type noMethod Student
    return json.Unmarshal(text, (*noMethod)(s))
}

作为示例,我使用 encoding/json 将 student 值转换为 json 对象键,但这不是必需的,您可以选择自己的格式。

https://play.golang.org/p/4BgZn4Y37Ww

好了,本文到此结束,带大家了解了《键为结构时造成Marshal/unMarshal问题》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

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