2 回答
TA贡献1875条经验 获得超5个赞
值的自定义处理可以通过实现接口的自定义类型来完成Marshaler。Something但是,您的类型格式不正确。它被定义为type Something interface{},而实际上应该是type Something struct:
type Something struct {
Id string `firestore:"id"`
NumberA JSONFloat `firestore:"numberA"`
NumberB JSONFloat `firestore:"numberB"`
NumberC JSONFloat `firestore:"numberC"`
}
type JSONFloat float64
func (j JSONFloat) MarshalJSON() ([]byte, error) {
v := float64(j)
if math.IsInf(j, 0) {
// handle infinity, assign desired value to v
// or say +/- indicates infinity
s := "+"
if math.IsInf(v, -1) {
s = "-"
}
return []byte(s), nil
}
return json.Marshal(v) // marshal result as standard float64
}
func (j *JSONFloat) UnsmarshalJSON(v []byte) error {
if s := string(v); s == "+" || s == "-" {
// if +/- indiciates infinity
if s == "+" {
*j = JSONFloat(math.Inf(1))
return nil
}
*j = JSONFloat(math.Inf(-1))
return nil
}
// just a regular float value
var fv float64
if err := json.Unmarshal(v, &fv); err != nil {\
return err
}
*j = JSONFloat(fv)
return nil
}
应该这样做
TA贡献1829条经验 获得超13个赞
我创建了xhhuango/json来支持 NaN、+Inf 和 -Inf。
type T struct {
N float64
IP float64
IN float64
}
func TestMarshalNaNAndInf(t *testing.T) {
s := T{
N: math.NaN(),
IP: math.Inf(1),
IN: math.Inf(-1),
}
got, err := Marshal(s)
if err != nil {
t.Errorf("Marshal() error: %v", err)
}
want := `{"N":NaN,"IP":+Inf,"IN":-Inf}`
if string(got) != want {
t.Errorf("Marshal() = %s, want %s", got, want)
}
}
func TestUnmarshalNaNAndInf(t *testing.T) {
data := []byte(`{"N":NaN,"IP":+Inf,"IN":-Inf}`)
var s T
err := Unmarshal(data, &s)
if err != nil {
t.Fatalf("Unmarshal: %v", err)
}
if !math.IsNaN(s.N) || !math.IsInf(s.IP, 1) || !math.IsInf(s.IN, -1) {
t.Fatalf("after Unmarshal, s.N=%f, s.IP=%f, s.IN=%f, want NaN, +Inf, -Inf", s.N, s.IP, s.IN)
}
}
- 2 回答
- 0 关注
- 146 浏览
添加回答
举报