dougou5844 2017-12-07 03:44
浏览 407
已采纳

解码JSON值,可以是字符串或数字

When I make an HTTP call to a REST API I may get the JSON value count back as a Number or String. I'ld like to marshal it to be an integer in either case. How can I deal with this in Go?.

  • 写回答

3条回答 默认 最新

  • doujin8476 2017-12-07 03:56
    关注

    Use the "string" field tag option to specify that strings should be converted to numbers. The documentation for the option is:

    The "string" option signals that a field is stored as JSON inside a JSON-encoded string. It applies only to fields of string, floating point, integer, or boolean types. This extra level of encoding is sometimes used when communicating with JavaScript programs:

    Here's an example use:

    type S struct {
        Count int `json:"count,string"`
    }
    

    playground example

    If the JSON value can be number or string, then unmarshal to interface{} and convert to int after unmarshaling:

    Count interface{} `json:"count,string"`
    

    Use this function to convert the interface{} value to an int:

    func getInt(v interface{}) (int, error) {
      switch v := v.(type) {
      case float64:
        return int(v), nil
      case string:
        c, err := strconv.Atoi(v)
        if err != nil {
           return 0, err
        }
      default:
        return 0, fmt.Errorf("conversion to int from %T not supported", v)
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥200 关于#c++#的问题,请各位专家解答!
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥15 绘制多分类任务的roc曲线时只画出了一类的roc,其它的auc显示为nan
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀