英文:
Differences in parsing json with a custom unmarshaller between golang versions
问题
我正在尝试将一些针对go1.3编写的代码移植到当前版本,并遇到了一个问题,不同版本之间的json解析行为不同。我们正在使用自定义的解码器来解析特定的日期格式。最近的版本似乎在字符串中添加了额外的引号,而1.3版本没有这样做。
这是一个错误还是有意的更改?在这种情况下,编写与不同版本兼容的代码的最佳方法是什么?只需查找所有使用自定义解码器的地方,如果有任何额外的引号,则始终去除它们吗?这样做会很遗憾,所以我希望有更好的方法。
package main
import "encoding/json"
import "fmt"
import "time"
type Timestamp1 time.Time
func (t *Timestamp1) UnmarshalJSON(b []byte) (err error) {
fmt.Println("String to parse as timestamp:", string(b))
parsedTime, err := time.Parse("2006-01-02T15:04:05", string(b))
if err == nil {
*t = Timestamp1(parsedTime)
return nil
} else {
return err
}
}
type S struct {
LastUpdatedDate Timestamp1 `json:"last_updated_date,string"`
}
func main() {
s := `{"last_updated_date" : "2015-11-03T10:00:00"}`
var s1 S
err := json.Unmarshal([]byte(s), &s1)
fmt.Println(err)
fmt.Println(s1)
}
以上是您提供的代码。
英文:
I am trying to port some code written against go1.3 to current versions and ran into a case where the json parsing behavior is different between versions. We are using a custom unmarshaller for parsing some specific date format. It looks like recent versions pass in the string with additional quotes which 1.3 did not.
Is this a bug or an intentional change? And whats the best way of writing code which is compatible with different versions in this situation. Just go looking for all places where a custom unmarshaller is in use always strip out extra quotes if any? It would be a pity to have to do that - so I am hoping there is a better way.
package main
import "encoding/json"
import "fmt"
import "time"
type Timestamp1 time.Time
func (t *Timestamp1) UnmarshalJSON(b []byte) (err error) {
fmt.Println("String to parse as timestamp:", string(b))
parsedTime, err := time.Parse("2006-01-02T15:04:05", string(b))
if err == nil {
*t = Timestamp1(parsedTime)
return nil
} else {
return err
}
}
type S struct {
LastUpdatedDate Timestamp1 `json:"last_updated_date,string"`
}
func main() {
s := `{"last_updated_date" : "2015-11-03T10:00:00"}`
var s1 S
err := json.Unmarshal([]byte(s), &s1)
fmt.Println(err)
fmt.Println(s1)
}
答案1
得分: 1
在1.5版本中修复了一个关于json:",string"
标签的错误。如果没有特殊原因需要它,你可以将其删除并简单地调整你的格式:
// 注意:时间需要加引号。
parsedTime, err := time.Parse("\"2006-01-02T15:04:05\"", string(b))
Playground: http://play.golang.org/p/LgWuKcPEuI.
这在1.3版本和1.5版本中都可以工作。
英文:
There was a bug concerning json:",string"
tag that was fixed in 1.5. If there isn't a particular reason you need it, you can remove it and simply adjust your format:
// N.B. time is in quotes.
parsedTime, err := time.Parse(`"2006-01-02T15:04:05"`, string(b))
Playground: http://play.golang.org/p/LgWuKcPEuI.
This should work in 1.3 as well as 1.5.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论