我发送此json:

{"origin":{"lat":23.589367061768648,"lng":58.42860314995051},"destination":null,"vehicle":"WATER_TANKER_600GL","scheduled_time":"2022-07-27T14:16:00Z04:00"}

Golang Gin处理函数:

func (config *Config) CreateOrder(c *gin.Context) {

    userID := auth.GetToken(c).ID()

    data := &struct {
        Origin        models.Origin       `json:"origin" binding:"required"`
        Vehicle       VehicleType         `json:"vehicle" binding:"required"`
        Destination   *models.Destination `json:"destination" `
        ScheduledTime *time.Time          `json:"scheduled_time"`
    }{}

    if err := c.ShouldBindWith(data, binding.JSON); err != nil {
        fmt.Println(err) // -> prints the below error
        res.UnprocessableEntity(c, fmt.Sprintf("%s", err))
        return
    }

// rest of the code
}

我发现这个错误:

parsing time "\"2022-07-27T14:16:00Z04:00\"" as "\"2006-01-02T15:04:05Z07:00\"": cannot parse "04:00\"" as "\""

推荐答案

请注意,JSON does not define a date or timestamp data type.可以将时间戳传输为JSON字符串,但如何解释或应如何解释时间戳字符串并不是一成不变的.标准库(encoding/json包)支持从JSON字符串中解组time.Time个值,但它通过要求它们遵守RFC 3339标准来实现,否则解组将失败.

time.Time实现json.UnmarshalerTime.UnmarshalJSON()声明JSON字符串必须在RFC 3339布局中,即:

RFC3339 = "2006-01-02T15:04:05Z07:00"

layout中的Z表示:

数字时区偏移格式如下:

"-0700"  ±hhmm
"-07:00" ±hh:mm
"-07"    ±hh

Replacing the sign in the format with a Z triggers the ISO 8601 behavior of printing Z instead of an offset for the UTC zone.因此:

"Z0700"  Z or ±hhmm
"Z07:00" Z or ±hh:mm
"Z07"    Z or ±hh

也就是说,如果时间有UTC偏移,则应为

"2022-07-27T14:16:00Z"

如果时间有+04:00个区域,则应为

"2022-07-27T14:16:00+04:00"

输入"2022-07-27T14:16:00Z04:00"对RFC 3339无效.请更改源以提供符合RFC 3339的时间戳字符串,或者如果您不能或不想,可以创建实现json.Unmarshaler的自定义类型,并自行处理此非RFC 3339格式.

Json相关问答推荐

Jolt Transformation—如果子对象为空,则将父对象更新为空

按照对象键的值对PostgreSQL JSONB对象进行排序'

将PostgreSQL转换为JSON对象

如何用JQ打印JSON文件的路径和键值

将部分数据字节解组到自定义 struct 中

将pyspark.sql.Rowtype数据转换为Json字符串,消除Azure Databricks NB中的值

错误:在 NX 工作区中找不到模块../swagger.json

迭代powershell双维json对象

如何在 jq 中按 IP 地址排序?

JOLT 获取带有动态键的数组

使用 REACT 从字段值中读取 JSON 元素

JOLT JSON 将值从一对多转换为一对一

使用 Jolt 变换将平面 json 转换为具有多个数组的嵌套 Json

如果 JSON 对象包含列表中的子字符串,则丢弃它们

JSON 语法错误:'unexpected number' 或 'JSON.parse: expected ',' or '}' after property value in object'

如何将 LinkedTreeMap 转换为 gson JsonObject

Jackson 动态属性名称

使用 jq 从 bash 中管道分隔的键和值创建 JSON

区分字符串和列表的 Pythonic 方式是什么?

如何在spark 上将json字符串转换为数据帧