JSON将整数字段解组成字符串

Tig*_*ine 5 json struct go unmarshalling

我正在努力将整数反序列化为字符串结构字段.struct字段是一个字符串,预计可以从我的库的用户分配.这就是为什么我希望它成为一个字符串,因为为了将它写入数据库,我实际上并不关心内部的价值.用户可以提供文本,但有些只是分配整数.

考虑这个结构:

type Test struct {
  Foo string
}
Run Code Online (Sandbox Code Playgroud)

有时我最终会得到一个有效的JSON值,但由于Foo字段是整数而不是字符串,因此不会反序列化到结构中:

{ "foo": "1" } // works
{ "foo": 1 } // doesn't
Run Code Online (Sandbox Code Playgroud)

json.Unmarshal将会出现以下错误: json: cannot unmarshal number into Go struct field test.Foo of type string

请参阅复制:https://play.golang.org/p/4Qau3umaVm

现在在其他JSON库(在其他语言中)我已经工作到目前为止,如果目标字段是一个字符串并且你得到一个整数,反序列化器通常只是将int包装在一个字符串中并完成它.这可以在Go中实现吗?

由于我无法真正控制数据的来源,我需要对此不json.Unmarshal敏感 - 另一种解决方案是定义Foo,因为interface{}它会使我的代码与类型断言等不必要地复杂化.

关于如何做到这一点的任何想法?我基本上需要倒数json:",string"

mko*_*iva 5

要处理大结构,您可以使用嵌入.

更新为不丢弃可能先前设置的字段值.

func (t *T) UnmarshalJSON(d []byte) error {
    type T2 T // create new type with same structure as T but without its method set!
    x := struct{
        T2 // embed
        Foo json.Number `json:"foo"`
    }{T2: T2(*t)} // don't forget this, if you do and 't' already has some fields set you would lose them

    if err := json.Unmarshal(d, &x); err != nil {
        return err
    }
    *t = T(x.T2)
    t.Foo = x.Foo.String()
    return nil
}
Run Code Online (Sandbox Code Playgroud)

https://play.golang.org/p/BytXCeHMvt

  • 很好的例子(但这不是[别名](https://golang.org/ref/spec#Alias_declarations)) (3认同)
  • 不,它从未被称为别名,因为它创建了一个新类型.并不意味着其他人在过去并没有把它称为"别名",但是我多年来一直尽力在这个问题上迂腐,特别是一旦提出真正的别名想法;)唯一_real_别名以前分别是`byte`和`rune`,分别用于`uint8`和`int32`. (3认同)