Help me with json unmarshal

93 views
Skip to first unread message

forfader

unread,
Mar 18, 2015, 12:14:25 AM3/18/15
to golan...@googlegroups.com
package main

import (
"encoding/json"
"fmt"
)

func main() {
var jsonBlob = []byte(`{"name": "Don Jones","emailAddress": "d...@gmail.com","password": "snapple","userId": "xxx"}`)
type User struct {
name  string
emailAddress string
password string
userId string
}
var user User
err := json.Unmarshal(jsonBlob, &user)
if err != nil {
fmt.Println("error:", err)
}
fmt.Printf("%+v", user)
}

When I run this, json.Unmarshal does not return an error, but the unmarshal does not work. None of the properties of user are set.

I'm missing something in my understanding of json support. What am I missing?

Thanks,
Michael-

Jesse McNelis

unread,
Mar 18, 2015, 12:24:37 AM3/18/15
to forfader, golang-nuts
On Wed, Mar 18, 2015 at 3:14 PM, forfader <mbur...@gmail.com> wrote:
> type User struct {
> name string
> emailAddress string
> password string
> userId string
> }

> When I run this, json.Unmarshal does not return an error, but the unmarshal
> does not work. None of the properties of user are set.
>
> I'm missing something in my understanding of json support. What am I
> missing?

The json package don't see the fields on your User type because
they're not exported.
The field names need to start with an uppercase letter and have a name
that matches the name in the object you're unmarshalling.
If the object you're unmarshalling has lowercase field names then
you'll need to add struct field tags to your User struct fields.
eg.
type User struct {
Name string `json:"name"`
EmailAddress string `json:"emailAddress"`
Password string `json:"password"`
UserId string `json:"userid"`
}

crbrox

unread,
Mar 23, 2015, 10:24:48 AM3/23/15
to golan...@googlegroups.com, mbur...@gmail.com, jes...@jessta.id.au
I think tags are only required if you to marshal (with lowercase)




To unmarshal JSON into a struct, Unmarshal matches incoming object keys to the keys used by Marshal (either the struct field name or its tag), preferring an exact match but also accepting a case-insensitive match.
Reply all
Reply to author
Forward
0 new messages