Why does JSON or XML not work?

Asked

Viewed 34 times

1

I got this guy:

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?

1 answer

2


To encode or decode data, the identifiers shall be exported. Exported identifiers start 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: https://play.golang.org/p/JkQ5gyo9DDx.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.