我正在尝试将一些 json 解组为一个结构并具有以下内容:
package main
import (
"encoding/json"
"fmt"
"strings"
"time"
)
type Added struct {
Added *time.Time `json:"added"`
}
func main() {
st := strings.NewReader(`{"added": ""}`)
a := &Added{}
err := json.NewDecoder(st).Decode(&a)
if err != nil {
panic(err)
}
fmt.Println(a)
}
运行以上结果:
panic: parsing time """" as ""2006-01-02T15:04:05Z07:00"": cannot parse """ as "2006"
好的,所以我尝试自定义编组器:
package main
import (
"encoding/json"
"fmt"
"strings"
"time"
)
type Added struct {
Added *MyTime `json:"added"`
}
func main() {
st := strings.NewReader(`{"added": ""}`)
a := &Added{}
err := json.NewDecoder(st).Decode(&a)
if err != nil {
panic(err)
}
fmt.Println(a)
}
type MyTime struct {
*time.Time
}
func (m *MyTime) UnmarshalJSON(data []byte) error {
// Ignore null, like in the main JSON package.
if string(data) == "null" || string(data) == `""` {
return nil
}
// Fractional seconds are handled implicitly by Parse.
tt, err := time.Parse(`"`+time.RFC3339+`"`, string(data))
*m = MyTime{&tt}
return err
}
然后我得到:
&{%!v(PANIC=runtime error: invalid memory address or nil pointer dereference)}
好的,现在我该怎么办?我只想处理来自 json 的“”值。
找到了带有完整示例的我的游乐场。
紫衣仙女
繁华开满天机
相关分类