This error occurs when you are trying to unmarshal a JSON number into a struct field that is not compatible with the number type.

To fix this issue, you can try the following:

  1. Make sure the struct field is of the correct type. For example, if the JSON number represents an integer, the struct field should be of type int or int64.

  2. Use a custom unmarshaler for the struct field. You can implement the json.Unmarshaler interface for the struct field and provide custom logic to convert the JSON number to the desired type.

Here's an example of how you can implement a custom unmarshaler for a struct field:

type MyStruct struct {
    NumberAsString string `json:"number"`
    NumberAsInt    int    `json:"-"`
}

func (s *MyStruct) UnmarshalJSON(data []byte) error {
    // Define a custom struct to unmarshal the JSON number
    type Number struct {
        Value interface{}
    }

    // Unmarshal the JSON number into the custom struct
    var n Number
    if err := json.Unmarshal(data, &n); err != nil {
        return err
    }

    // Convert the number to the desired type
    switch v := n.Value.(type) {
    case float64:
        s.NumberAsInt = int(v)
    case string:
        intValue, err := strconv.Atoi(v)
        if err != nil {
            return err
        }
        s.NumberAsInt = intValue
    default:
        return fmt.Errorf("unexpected number type: %T", v)
    }

    return nil
}

In this example, the NumberAsString field is used to unmarshal the JSON number as a string, while the NumberAsInt field is used to store the converted integer value.

Note that this approach can be extended to handle other number types or custom conversions as needed

golang can not unmarshal number into struct field

原文地址: https://www.cveoy.top/t/topic/it4A 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录