duandu1915 2015-05-07 16:13 采纳率: 100%
浏览 26
已采纳

解组datastore.ByteString去

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 ??

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条回答 默认 最新

  • dongshi6844 2015-05-07 17:18
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?