doumei3828 2017-08-30 19:37
浏览 109
已采纳

JSON解组整数字段为字符串

I am struggling with deserializing a integer into a string struct field. The struct field is a string and is expected to be assignable from users of my library. That's why I want it to be a string, since for the purpose of writing it to the database I actually don't care about the value inside. The users can supply text, but some just assign integers.

Consider this struct:

type Test struct {
  Foo string
}

Sometimes I end up with a JSON value that is valid but won't deserialize into the struct due to the Foo field being a integer instead of a string:

{ "foo": "1" } // works
{ "foo": 1 } // doesn't

json.Unmarshal will blow up with the following error: json: cannot unmarshal number into Go struct field test.Foo of type string

See the reproduction: https://play.golang.org/p/4Qau3umaVm

Now in every other JSON library (in other languages) I have worked in so far, if the target field is a string and you get a integer the deserializer will usually just wrap the int in a string and be done with it. Can this be achieved in Go?

Since I can't really control how the data comes in I need to make json.Unmarshal unsensitive to this - the other solution would be to define Foo as interface{} which needlessly complicates my code with type assertions etc..

Any ideas on how to do this? I basically need the inverse of json:",string"

  • 写回答

2条回答 默认 最新

  • dotif64826 2017-08-30 20:02
    关注

    To handle big structs you can use embedding.

    Updated to not discard possibly previously set field values.

    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
    }
    

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 ensp,用局域网解决
  • ¥15 Python语言实验
  • ¥15 我每周要在投影仪优酷上自动连续播放112场电影,我每一周遥控操作一次投影仪,并使得电影永远不重复播放,请问怎样操作好呢?有那么多电影看吗?
  • ¥20 电脑重启停留在grub界面,引导出错需修复
  • ¥15 matlab透明图叠加
  • ¥50 基于stm32l4系列 使用blunrg-ms的ble gatt 创建 hid 服务失败
  • ¥150 计算DC/DC变换器平均模型中的参数mu
  • ¥25 C语言代码,大家帮帮我
  • ¥15 请问以下文字内容及对应编码是用了什么加密算法或压缩算法呢?
  • ¥50 关于#html5#的问题:H5页面用户手机返回的时候跳转到指定页面例如(语言-javascript)