{"id":207830,"date":"2025-07-08T09:50:55","date_gmt":"2025-07-08T01:50:55","guid":{"rendered":"https:\/\/server.hk\/cnblog\/207830\/"},"modified":"2025-07-08T09:50:55","modified_gmt":"2025-07-08T01:50:55","slug":"%e4%bd%bf%e7%94%a8-go-%e5%8f%8d%e5%b0%84%e5%af%b9%e5%a4%8d%e6%9d%82%e5%af%b9%e8%b1%a1%e8%bf%9b%e8%a1%8c-unmarshal-%e6%96%b9%e6%b3%95","status":"publish","type":"post","link":"https:\/\/server.hk\/cnblog\/207830\/","title":{"rendered":"\u4f7f\u7528 Go \u53cd\u5c04\u5bf9\u590d\u6742\u5bf9\u8c61\u8fdb\u884c Unmarshal \u65b9\u6cd5"},"content":{"rendered":"<p><b><\/b> <\/p>\n<p>\u5f53\u524d\u4f4d\u7f6e\uff1a <span>&gt;<\/span> <span>&gt;<\/span> <span>&gt;<\/span> <span>&gt;<\/span> <span>\u4f7f\u7528 Go \u53cd\u5c04\u5bf9\u590d\u6742\u5bf9\u8c61\u8fdb\u884c Unmarshal \u65b9\u6cd5<\/span><\/p>\n<p><span>\u6765\u6e90\uff1astackoverflow<\/span><br \/>\n<span>2024-04-25 21:51:37<\/span><br \/>\n<span><i><\/i>0\u6d4f\u89c8<\/span><br \/>\n<span style=\"cursor: pointer\"><i><\/i>\u6536\u85cf<\/span> <\/p>\n<p>\u79ef\u7d2f\u77e5\u8bc6\uff0c\u80dc\u8fc7\u79ef\u84c4\u91d1\u94f6\uff01\u6bd5\u7adf\u5728Golang\u5f00\u53d1\u7684\u8fc7\u7a0b\u4e2d\uff0c\u4f1a\u9047\u5230\u5404\u79cd\u5404\u6837\u7684\u95ee\u9898\uff0c\u5f80\u5f80\u90fd\u662f\u4e00\u4e9b\u7ec6\u8282\u77e5\u8bc6\u70b9\u8fd8\u6ca1\u6709\u638c\u63e1\u597d\u800c\u5bfc\u81f4\u7684\uff0c\u56e0\u6b64\u57fa\u7840\u77e5\u8bc6\u70b9\u7684\u79ef\u7d2f\u662f\u5f88\u91cd\u8981\u7684\u3002\u4e0b\u9762\u672c\u6587\u300a\u4f7f\u7528 Go \u53cd\u5c04\u5bf9\u590d\u6742\u5bf9\u8c61\u8fdb\u884c Unmarshal \u65b9\u6cd5\u300b\uff0c\u5c31\u5e26\u5927\u5bb6\u8bb2\u89e3\u4e00\u4e0b\u77e5\u8bc6\u70b9\uff0c\u82e5\u662f\u4f60\u5bf9\u672c\u6587\u611f\u5174\u8da3\uff0c\u6216\u8005\u662f\u60f3\u641e\u61c2\u5176\u4e2d\u67d0\u4e2a\u77e5\u8bc6\u70b9\uff0c\u5c31\u8bf7\u4f60\u7ee7\u7eed\u5f80\u4e0b\u770b\u5427~<\/p>\n<p> \u95ee\u9898\u5185\u5bb9<br \/>\n <\/p>\n<p>\u6211\u5f00\u59cb\u7f16\u5199\u66f4\u590d\u6742\u7684 go \u4ee3\u7801\uff0c\u6211\u7684\u5bf9\u8c61\u8282\u70b9\u5c06\u5217\u8868\u4ece json \u5bf9\u8c61\u8f6c\u6362\u4e3a\u5177\u6709\u7279\u5b9a\u952e\u7684\u6620\u5c04\u3002\u6b64\u64cd\u4f5c\u5e2e\u52a9\u6211\u52a0\u5feb\u7b97\u6cd5\u901f\u5ea6\u3002\u4f46\u6211\u73b0\u5728\u6709\u4e00\u4e2a\u95ee\u9898\uff0c\u6211\u7684\u5bb9\u5668\u7ed3\u6784\u6709\u51e0\u4e2a\u590d\u6742\u7684 json\uff0c\u6211\u65e0\u6cd5\u7f16\u5199\u901a\u7528\u89e3\u51b3\u65b9\u6848\u6765\u5b9e\u73b0\u901a\u7528\u89e3\u51b3\u65b9\u6848\u3002\u6211\u60f3\u5230\u7684\u552f\u4e00\u65b9\u6cd5\u662f\u4f7f\u7528\u5927\u5f00\u5173\u76d2\uff0c\u4f46\u6211\u8ba4\u4e3a\u8fd9\u4e0d\u662f\u6b63\u786e\u7684\u89e3\u51b3\u65b9\u6848\u3002<\/p>\n<p>\u8fd9\u662f\u6211\u76ee\u524d\u7684\u4ee3\u7801\uff0c\u5176\u4e2d <code>statuschannel<\/code> \u662f\u4ee3\u7801\u4e2d\u7684\u6620\u5c04\uff0c\u4f46\u5b83\u662f json \u5b57\u7b26\u4e32\u4e2d\u7684\u5217\u8868<\/p>\n<pre>type metricone struct {\n    \/\/ internal id to identify the metric\n    id int `json:\"-\"`\n    \/\/ version of metrics format, it is used to migrate the\n    \/\/ json payload from previous version of plugin.\n    version int `json:\"version\"`\n    \/\/ name of the metrics\n    name   string  `json:\"metric_name\"`\n    nodeid string  `json:\"node_id\"`\n    color  string  `json:\"color\"`\n    osinfo *osinfo `json:\"os_info\"`\n    \/\/ timezone where the node is located\n    timezone string `json:\"timezone\"`\n    \/\/ array of the up_time\n    uptime []*status `json:\"up_time\"`\n    \/\/ map of informatonof channel information\n    channelsinfo map[string]*statuschannel `json:\"channels_info\"`\n}\n\nfunc (instance *metricone) marshaljson() ([]byte, error) {\n    jsonmap := make(map[string]interface{})\n    reflecttype := reflect.typeof(*instance)\n    reflectvalue := reflect.valueof(*instance)\n    nfiled := reflectvalue.type().numfield()\n\n    for i := 0; i &lt; nfiled; i++ {\n        key := reflecttype.field(i)\n        valuefiled := reflectvalue.field(i)\n        jsonname := key.tag.get(\"json\")\n        switch jsonname {\n        case \"-\":\n            \/\/ skip\n            continue\n        case \"channels_info\":\n            \/\/ todo convert the map[string]*statuschannel in a list of statuschannel\n            statuschannels := make([]*statuschannel, 0)\n            for _, value := range valuefiled.interface().(map[string]*statuschannel) {\n                statuschannels = append(statuschannels, value)\n            }\n            jsonmap[jsonname] = statuschannels\n        default:\n            jsonmap[jsonname] = valuefiled.interface()\n        }\n    }\n\n    return json.marshal(jsonmap)\n}\n\nfunc (instance *metricone) unmarshaljson(data []byte) error {\n    var jsonmap map[string]interface{}\n    err := json.unmarshal(data, &amp;jsonmap)\n    if err != nil {\n        log.getinstance().error(fmt.sprintf(\"error: %s\", err))\n        return err\n    }\n    instance.migrate(jsonmap)\n    reflectvalue := reflect.valueof(instance)\n    reflectstruct := reflectvalue.elem()\n    \/\/ reflecttype := reflectvalue.type()\n    for key, value := range jsonmap {\n        fieldname, err := utils.getfieldname(key, \"json\", *instance)\n        if err != nil {\n            log.getinstance().info(fmt.sprintf(\"error: %s\", err))\n            if strings.contains(key, \"dev_\") {\n                log.getinstance().info(\"dev propriety skipped if missed\")\n                continue\n            }\n            return err\n        }\n        field := reflectstruct.fieldbyname(*fieldname)\n        fieldtype := field.type()\n        filedvalue := field.interface()\n        val := reflect.valueof(filedvalue)\n\n        switch key {\n        case \"channels_info\":\n            statuschannelsmap := make(map[string]*statuschannel)\n            toarray := value.([]interface{})\n            for _, status := range toarray {\n                var statustype statuschannel\n                jsonval, err := json.marshal(status)\n                if err != nil {\n                    return err\n                }\n                err = json.unmarshal(jsonval, &amp;statustype)\n                if err != nil {\n                    return err\n                }\n                statuschannelsmap[statustype.channelid] = &amp;statustype\n            }\n            field.set(reflect.valueof(statuschannelsmap))\n        default:\n            field.set(val.convert(fieldtype))\n        }\n    }\n    return nil\n}<\/pre>\n<p>\u5f53\u6211\u89e3\u7801\u5bf9\u8c61\u65f6\uff0c\u6211\u6536\u5230\u4ee5\u4e0b\u9519\u8bef\uff1a<\/p>\n<pre>  go-metrics-reported git:(dev)  make check\ngo test -v .\/...\n?       github.com\/OpenLNMetrics\/go-metrics-reported\/cmd\/go-metrics-reported    [no test files]\n?       github.com\/OpenLNMetrics\/go-metrics-reported\/init\/persistence   [no test files]\n=== RUN   TestJSONSerializzation\n--- PASS: TestJSONSerializzation (0.00s)\n=== RUN   TestJSONDeserializzation\n--- FAIL: TestJSONDeserializzation (0.00s)\npanic: reflect.Value.Convert: value of type map[string]interface {} cannot be converted to type *plugin.osInfo [recovered]\n    panic: reflect.Value.Convert: value of type map[string]interface {} cannot be converted to type *plugin.osInfo\n\ngoroutine 7 [running]:\ntesting.tRunner.func1.1(0x61b440, 0xc0001d69a0)\n    \/home\/vincent\/.gosdk\/go\/src\/testing\/testing.go:1072 +0x30d\ntesting.tRunner.func1(0xc000001e00)\n    \/home\/vincent\/.gosdk\/go\/src\/testing\/testing.go:1075 +0x41a\npanic(0x61b440, 0xc0001d69a0)\n    \/home\/vincent\/.gosdk\/go\/src\/runtime\/panic.go:969 +0x1b9\nreflect.Value.Convert(0x6283e0, 0xc0001bb1a0, 0x15, 0x6b93a0, 0x610dc0, 0x610dc0, 0xc00014cb40, 0x196)\n    \/home\/vincent\/.gosdk\/go\/src\/reflect\/value.go:2447 +0x229\ngithub.com\/OpenLNMetrics\/go-metrics-reported\/internal\/plugin.(*MetricOne).UnmarshalJSON(0xc00014cb00, 0xc0001d8000, 0x493, 0x500, 0x7f04d01453d8, 0xc00014cb00)\n    \/home\/vincent\/Github\/OpenLNMetrics\/go-metrics-reported\/internal\/plugin\/metrics_one.go:204 +0x5b3\nencoding\/json.(*decodeState).object(0xc00010be40, 0x657160, 0xc00014cb00, 0x16, 0xc00010be68, 0x7b)\n    \/home\/vincent\/.gosdk\/go\/src\/encoding\/json\/decode.go:609 +0x207c\nencoding\/json.(*decodeState).value(0xc00010be40, 0x657160, 0xc00014cb00, 0x16, 0xc000034698, 0x54ec19)\n    \/home\/vincent\/.gosdk\/go\/src\/encoding\/json\/decode.go:370 +0x6d\nencoding\/json.(*decodeState).unmarshal(0xc00010be40, 0x657160, 0xc00014cb00, 0xc00010be68, 0x0)\n    \/home\/vincent\/.gosdk\/go\/src\/encoding\/json\/decode.go:180 +0x1ea\nencoding\/json.Unmarshal(0xc0001d8000, 0x493, 0x500, 0x657160, 0xc00014cb00, 0x500, 0x48cba6)\n    \/home\/vincent\/.gosdk\/go\/src\/encoding\/json\/decode.go:107 +0x112\ngithub.com\/OpenLNMetrics\/go-metrics-reported\/internal\/plugin.TestJSONDeserializzation(0xc000001e00)\n    \/home\/vincent\/Github\/OpenLNMetrics\/go-metrics-reported\/internal\/plugin\/metric_one_test.go:87 +0x95\ntesting.tRunner(0xc000001e00, 0x681000)\n    \/home\/vincent\/.gosdk\/go\/src\/testing\/testing.go:1123 +0xef\ncreated by testing.(*T).Run\n    \/home\/vincent\/.gosdk\/go\/src\/testing\/testing.go:1168 +0x2b3\nFAIL    github.com\/OpenLNMetrics\/go-metrics-reported\/internal\/plugin    0.008s\n?       github.com\/OpenLNMetrics\/go-metrics-reported\/pkg\/db [no test files]\n?       github.com\/OpenLNMetrics\/go-metrics-reported\/pkg\/graphql    [no test files]\n?       github.com\/OpenLNMetrics\/go-metrics-reported\/pkg\/log    [no test files]\n?       github.com\/OpenLNMetrics\/go-metrics-reported\/pkg\/utils  [no test files]\nFAIL\nmake: *** [Makefile:15: check] Error 1<\/pre>\n<p>\u6709\u4eba\u53ef\u4ee5\u89e3\u91ca\u4e00\u4e0b\u6211\u5982\u4f55\u4ee5\u901a\u7528\u65b9\u5f0f\u6267\u884c\u6b64\u64cd\u4f5c\u5417\uff1f<\/p>\n<p> <\/p>\n<h2>\u6b63\u786e\u7b54\u6848<\/h2>\n<p> <\/p>\n<pre>type metricone struct {\n    \/\/ ...\n\n    \/\/ have this field be ignored.\n    channelsinfo map[string]*statuschannel `json:\"-\"`\n}\n<\/pre>\n<pre>func (m metricone) marshaljson() ([]byte, error) {\n    \/\/ declare a new type using the definition of metricone,\n    \/\/ the result of this is that m will have the same structure\n    \/\/ as metricone but none of its methods (this avoids recursive\n    \/\/ calls to marshaljson).\n    \/\/\n    \/\/ also because m and metricone have the same structure you can\n    \/\/ easily convert between those two. e.g. m(metricone{}) and\n    \/\/ metricone(m{}) are valid expressions.\n    type m metricone\n\n    \/\/ declare a new type that has a field of the \"desired\" type and\n    \/\/ also **embeds** the m type. embedding promotes m's fields to t\n    \/\/ and encoding\/json will marshal those fields unnested\/flattened, \n    \/\/ i.e. at the same level as the channels_info field.\n    type t struct {\n        m\n        channelsinfo []*statuschannel `json:\"channels_info\"`\n    }\n\n    \/\/ move map elements to slice\n    channels := make([]*statuschannel, 0, len(m.channelsinfo))\n    for _, c := range m.channelsinfo {\n        channels = append(channels, c)\n    }\n\n    \/\/ pass in an instance of the new type t to json.marshal.\n    \/\/ for the embedded m field use a converted instance of the receiver.\n    \/\/ for the channelsinfo field use the channels slice.\n    return json.marshal(t{\n        m:            m(m),\n        channelsinfo: channels,\n    })\n}\n<\/pre>\n<pre>\/\/ Same as MarshalJSON but in reverse.\nfunc (m *MetricOne) UnmarshalJSON(data []byte) error {\n    type M MetricOne\n    type T struct {\n        *M\n        ChannelsInfo []*statusChannel `json:\"channels_info\"`\n    }\n    t := T{M: (*M)(m)}\n    if err := json.Unmarshal(data, &amp;t); err != nil {\n        panic(err)\n    }\n\n    m.ChannelsInfo = make(map[string]*statusChannel, len(t.ChannelsInfo))\n    for _, c := range t.ChannelsInfo {\n        m.ChannelsInfo[c.ChannelId] = c\n    }\n\n    return nil\n}\n<\/pre>\n<p>\u672c\u7bc7\u5173\u4e8e\u300a\u4f7f\u7528 Go \u53cd\u5c04\u5bf9\u590d\u6742\u5bf9\u8c61\u8fdb\u884c Unmarshal \u65b9\u6cd5\u300b\u7684\u4ecb\u7ecd\u5c31\u5230\u6b64\u7ed3\u675f\u5566\uff0c\u4f46\u662f\u5b66\u65e0\u6b62\u5883\uff0c\u60f3\u8981\u4e86\u89e3\u5b66\u4e60\u66f4\u591a\u5173\u4e8eGolang\u7684\u76f8\u5173\u77e5\u8bc6\uff0c\u8bf7\u5173\u6ce8\u516c\u4f17\u53f7\uff01<\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u5f53\u524d\u4f4d\u7f6e\uff1a &gt; &gt; &#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[4925],"tags":[],"class_list":["post-207830","post","type-post","status-publish","format-standard","hentry","category-4925"],"_links":{"self":[{"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/posts\/207830","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/comments?post=207830"}],"version-history":[{"count":0,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/posts\/207830\/revisions"}],"wp:attachment":[{"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/media?parent=207830"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/categories?post=207830"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/tags?post=207830"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}