FYI:

Serializing a struct to json works without having to specify struct tags:

type foo struct {
    Name string
    Age int
}

f := foo{ "Bob", 40 }

serializes ("marshals") into

{
    "Name" : "Bob",
    "Age" : 40
}

No struct tags needed.  The only time you need struct tags is if you want
to change the json name of one of the fields from being the same as the
field name.  This is most commonly done to lowercase the field names when
interoperating with an existing json service.  Note that only exported
fields can be marshaled/unmarshaled, which is why you often see stuff like
this:

type foo struct {
    Name string `json:"name"`
    Age int `json:"age"`
}

This lets the json package translate from the lowercase json name to the
uppercase field name (and vice versa).  But when we control both ends of
serialization (like in the api params package), we don't need to lowercase
anything (in which case we can leave out the struct tags entirely).

Struct tags that are the same as the name of field are never needed:

type SomeResult struct {
Error *Error                    `json:"Error"`
Somethings []Something `json:"Somethings"`
}

The above is totally unnecessary... those fields will already serialize
into "Error" and "Somethings".  There's a bunch of this in the
apiserver/params package... you don't need it, so don't do it.   It just
causes confusion, because it looks like you're changing the name from the
default, even though you're not.

-Nate
-- 
Juju-dev mailing list
Juju-dev@lists.ubuntu.com
Modify settings or unsubscribe at: 
https://lists.ubuntu.com/mailman/listinfo/juju-dev

Reply via email to