Unmarshal datastore.ByteString go

huangapple go评论86阅读模式
英文:

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&#39;m getting  unmarshal error, i can&#39;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 (
    	&quot;encoding/json&quot;
    	&quot;fmt&quot;
    	&quot;google.golang.org/appengine/datastore&quot;
    )
    
    type User struct {
    	SubscriptionToken datastore.ByteString
    }
    
    func main() {
    	u := new(User)
    	str := &quot;{\&quot;SubscriptionToken\&quot;:\&quot;YWR66969hjgkgkgo\&quot;}&quot;
    	err := json.Unmarshal([]byte(str), &amp;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 &amp;User{SubscriptionToken: StringToByteString(u.SubscriptionToken)}
}

So, unmarshal into the jsonUser type then convert it to a User

huangapple
  • 本文由 发表于 2015年5月8日 00:13:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/30106494.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定