Why does JSON or XML not work?

1

I have this type:

type S struct {
    a string    'json:"a" xml:"a"'
    b int       'json:"b" xml:"b"'
    c time.Time 'json:"c" xml:"c"'
}

But neither JSON nor XML works:

s := S{a: "Olá", b: 42, c: time.Now()}
jsonTexto, err := json.Marshal(s)
fmt.Printf("json: %s %v\n", jsonTexto, err)
// json: {} <nil>
xmlTexto, err := xml.Marshal(s)
fmt.Printf("xml : %s %v\n", xmlTexto, err)
// xml : <S></S> <nil>

Why?

    
asked by anonymous 27.10.2018 / 11:32

1 answer

2

To encode or decode data, identifiers must be exported . The exported identifiers begin with a capital letter:

type S struct {
    A string    'json:"a" xml:"a"'
    B int       'json:"b" xml:"b"'
    C time.Time 'json:"c" xml:"c"'
}

// ...

s := S{A: "Olá", B: 42, C: time.Now()}
jsonTexto, err := json.Marshal(s)
fmt.Printf("json: %s %v\n", jsonTexto, err)
// json: {"a":"Olá","b":42,"c":"2009-11-10T23:00:00Z"} <nil>
xmlTexto, err := xml.Marshal(s)
fmt.Printf("xml : %s %v\n", xmlTexto, err)
// xml : <S><a>Olá</a><b>42</b><c>2009-11-10T23:00:00Z</c></S> <nil>

Playground: link .

    
27.10.2018 / 11:32