英文:
Unmarshal datastore.ByteString go
问题
嗨,我正在尝试解组包含ByteString字段的数据存储实体。
但是我遇到了解组错误,我无法找到一种解组的方法。
我应该创建自己的PropertyLoadSaver吗?
json: 无法将字符串解组为类型为datastore.ByteString的Go值
package main
import (
"encoding/json"
"fmt"
"google.golang.org/appengine/datastore"
)
type User struct {
SubscriptionToken datastore.ByteString
}
func main() {
u := new(User)
str := "{\"SubscriptionToken\":\"YWR66969hjgkgkgo\"}"
err := json.Unmarshal([]byte(str), &u)
if err != nil {
fmt.Println(err)
}
fmt.Println(u)
}
以上是你要翻译的内容。
<details>
<summary>英文:</summary>
Hi im trying to unmarshal datastore entity that contain **ByteString** field.
But i'm getting unmarshal error, i can't figure out a way to unmarshal it
Should i create my own [PropertyLoadSaver][1] ??
json: cannot unmarshal string into Go value of type
datastore.ByteString
package main
import (
"encoding/json"
"fmt"
"google.golang.org/appengine/datastore"
)
type User struct {
SubscriptionToken datastore.ByteString
}
func main() {
u := new(User)
str := "{\"SubscriptionToken\":\"YWR66969hjgkgkgo\"}"
err := json.Unmarshal([]byte(str), &u)
if err != nil {
fmt.Println(err)
}
fmt.Println(u)
}
[1]: https://cloud.google.com/appengine/docs/go/datastore/reference#hdr-The_PropertyLoadSaver_Interface
</details>
# 答案1
**得分**: 1
你需要在这里使用一些中间类型。JSON只是一个字符串,你不能直接将其解组为`ByteString`,而不进行一些自定义的解组实现。个人建议使用以下方式:
```go
type jsonUser struct {
SubscriptionToken string
}
type User struct {
SubscriptionToken datastore.ByteString
}
func NewUser(u jsonUser) *User {
return &User{SubscriptionToken: StringToByteString(u.SubscriptionToken)}
}
因此,将其解组为jsonUser
类型,然后将其转换为User
类型。
英文:
You need to use some intermediate type here. The json simply has a string, you can't directly unmarshal it into a ByteString
without doing some custom unmarshaling implementation. Personally I would just use something like;
type jsonUser struct {
SubscriptionToken string
}
type User struct {
SubscriptionToken datastore.ByteString
}
Then provide a conversion method;
func NewUser(u jsonUser) *User {
return &User{SubscriptionToken: StringToByteString(u.SubscriptionToken)}
}
So, unmarshal into the jsonUser
type then convert it to a User
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论