无法在 go 中解组数据

问题描述 投票:0回答:1

我收到此错误:

cannot unmarshal string into Go struct field Attributes.length of type float64
但我试图用小写字母来解组该字段,这确实是一个数字。 为什么会出错?

注意标签:

json:"length"
,它应该让我得到小写字段,对吧?

这里是游乐场,如果你想重现它https://go.dev/play/p/v7EWz5OGou4


import (
    "encoding/json"
    "fmt"
)

const problematicData = `{
    "length": 3350,
    "Length": "3350"
}`

type Attributes struct {
    Length float64 `json:"length"`
}

func main() {
    var attributes Attributes
    err := json.Unmarshal([]byte(problematicData), &attributes)
    fmt.Println("error:", err)
}
json go
1个回答
0
投票

Golang 的 Unmarshal 函数默认不区分大小写。请参阅https://pkg.go.dev/encoding/json#Unmarshal

更喜欢完全匹配,但也接受不区分大小写的匹配

为了使其在您的情况下工作,您需要实现一个自定义解组器。

以下内容将接受 json 中的

length
键。游乐场:https://go.dev/play/p/OAUdMBc0Szi

package main

import (
    "encoding/json"
    "fmt"
)

const problematicData = `{
    "length": 3350,
    "Length": "3350"
}`

type Attributes struct {
    Length float64 `json:"length"`
}

func (b *Attributes) UnmarshalJSON(data []byte) error {
    var v map[string]any
    if err := json.Unmarshal(data, &v); err != nil {
        return err
    }
    for key, v := range v {
        if key != "length" {
            continue
        }
        if floatValue, ok := v.(float64); ok {
            b.Length = floatValue
        }
    }
    return nil
}

func main() {
    var attributes Attributes
    err := json.Unmarshal([]byte(problematicData), &attributes)
    fmt.Println("error:", err, attributes)
}
© www.soinside.com 2019 - 2024. All rights reserved.