duanjing3656 2017-10-30 06:16
浏览 46
已采纳

是否可以安全地假设特定结构上的json.Marshall不可能失败?

I have read this question which asks whether json.Marshal can fail on any input and based on the answers it looks like for my situation it can't fail. My situation is the following:

I have a specific struct (no nesting, no arrays, just strings, ints of various types, bools). I need to marshal it into a json. Can it ever fail?

In more specific example:

type some struct {
    F1 string `json:"f1"`
    F2 uint32 `json:"f2"`
    F3 int64  `json:"f3"`
    F4 bool   `json:"f4"`
}

func doSomething(s some) (string, error) {
    data, err := json.Marshal(s)
    if err != nil {
        return "", err
    }
    return string(data), nil
}

Can doSomething ever fail? If yes, please provide an input, otherwise explain why not. Based on my current knowledge it can't.

  • 写回答

1条回答 默认 最新

  • dongwo2772 2017-10-30 08:01
    关注

    There are three potential error sources I can see here:

    1. strings and various UTF8 stuff

    2. int64. Numbers in JSON are usually treated as float64, so a pedantic implementation could return an error for numbers with absolute values bigger than 2^53 because they could be dangerous.

    3. reflect.

    1 and 2 don't currently happen (the functions in encoding/json don't return errors or panic). I haven't dug into the code of reflect to verify 3, but this is one of those trivially testable cases. Either it fails on the first attempt or always works.

    On the other hand. In the past the json encoder would return errors if strings contained invalid UTF8 characters. It no longer does that, but this points to an important principle - things change. Just because a certain error isn't returned today doesn't mean that there won't be errors in the future. The function is defined to return errors. This means that it is perfectly valid for the standard library developers to start returning new errors in the future for things that might not be errors today. So the answer is - yes, it can fail. Maybe not today but code that depends on a particular version of a standard library is bad code.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换