ErickSkrauch ErickSkrauch - 5 months ago 35
JSON Question

How to serialize to json embed structure in golang

I'm just starting to learn Go, but I can not make out current task. I need to serialize the structure consisting of nested structures.

package main

import (
"encoding/json"
"fmt"
)

type Metadata struct {
model string
}

type Texture struct {
url string
hash string
metadata *Metadata
}

type Response struct {
SKIN *Texture
}

func main() {
response := Response{}
textures := &Texture{
url: "http://ely.by",
hash: "123123123123123123",
}
metadata := &Metadata{
model: "slim",
}

textures.metadata = metadata
response.SKIN = textures

result, _ := json.Marshal(response)
fmt.Println(string(result))
}


Always output only {"SKIN":{}}. Expected value is:

{
"SKIN": {
"url": "http://ely.by",
"hash": "123123123123123123",
"metadata": {
"model": "slim"
}
}
}


I created this example in a sandbox https://play.golang.org/p/IHktK6E33N.

Answer

You need to export your fields (make the names capitalized):

type Metadata struct {
    Model string
}

type Texture struct {
    Url      string
    Hash     string
    Metadata *Metadata
}

Updated playground example:

https://play.golang.org/p/d-d4SJbCpH