Unmarshal JSON Object to struct in Go - Result is empty [duplicate]

血红的双手。 提交于 2021-02-05 10:49:26

问题


I'm trying to unmarshal a json object to struct in Go. I tried to stick to this example but I can't get it to work. The result stays empty.

Code:

package main

import (
    "encoding/json"
    "fmt"
)

type MyObject struct {
    id     string
    pubKey string
}

func main() {
    x := `{"id":"abc","pubKey":"QIDAQAB"}`
    fmt.Println("Input: ", x)

    var myObject MyObject
    json.Unmarshal([]byte(x), &myObject)

    fmt.Println("Output: ", myObject)
}

Output:

Input:  {"id":"abc","pubKey":"QIDAQAB"}
Output:  { }

Playground

I found a lot of similar questions but I can't even see a difference between the working example and my non-working code. What am I missing?


回答1:


Fields of struct you want to Marshal or Unmarshal must be exported.
Check it out: http://blog.golang.org/json-and-go

The json package only accesses the exported fields of struct types (those that begin with an uppercase letter). Therefore only the the exported fields of a struct will be present in the JSON output.

Working sample: Go playground



来源:https://stackoverflow.com/questions/32438306/unmarshal-json-object-to-struct-in-go-result-is-empty

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!