ErickSkrauch
ErickSkrauch

Reputation: 81

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.

Upvotes: 1

Views: 830

Answers (1)

eduncan911
eduncan911

Reputation: 17624

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

Upvotes: 3

Related Questions