Documentation ¶
Overview ¶
Package jsonface enables JSON Unmarshalling into Go Interfaces. This enables you to isolate your data type design from your deserialization logic.
When writing Go programs, I often want to create types that contain interface members like this:
type ( Instrument interface { Play() } Bell struct { BellPitch string } // I am using contrived field names Drum struct { DrumSize float64 } // to keep this example simple. BandMember struct { Name string Inst Instrument // <---- Interface Member } )
...But if I want to serialize/deserialize a BandMember using JSON, I'm going to have a bit of a problem because Go's json package can't unmarshal into an interface. Therefore, I need to define some custom unmarshalling logic at the BandMember level. This is not ideal, since the logic should really belong to Instrument, not BandMember. It becomes especially problematic if I have other data types that also contain Instrument members because then the unmarshalling complexity spreads there too!
This jsonface package enables me to define the unmarshalling logic at the Instrument level, avoiding the leaky-complexity described above.
Also note, the example above just shows a very simple interface struct field, but jsonface is very general; It can handle any data structure, no matter how deep or complex.
See the included examples for more usage information.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AddGlobalCB ¶
AddGlobalCB adds an entry to the global callback registry. Then, when GlobalUnmarshal() is called, this global registry will be used to perform the unmarshalling. You will normally call AddGlobalCB() during program initialization (from an init() function) to register your unmarshallable interfaces.
func GlobalUnmarshal ¶
GlobalUnmarshal uses the global callback registry (created by the AddGlobalCB() funcion) to unmarshal data.
func ResetGlobalCBs ¶
func ResetGlobalCBs()
ResetGlobalCBs removes all definitions from the global callback registry. You probably shouldn't use this -- I just need to use it from my unit tests because Go runs all tests consecutively without resetting the namespace, and so my tests conflict with eachother. I need to use this to reset the registry between tests.
If you think you need this, instead consider using Unmarshal() and passing in your own CBMap.
func Unmarshal ¶
Unmarshal uses the provided CBMap to perform unmarshalling. It does not use the global callback registry. Most users will want to use GlobalUnmarshal() instead, but this function is provided for extra flexibility in advanced situations.
Some "advanced situations" where you might want to use Unmarshal() are:
You want to unmarshal many objects in parallel. (GlobalUnmarshal uses a lock, and therefore only processes items in series.)
You only want the callback registration to be temporary.
You are creating and *destroying* types dynamically.
You need to avoid name collisions. (Not usually a problem.)
Example ¶
package main // This example shows how to use the jsonface.Unmarshal() function directly for // advanced situations. For normal cases, you'd use jsonface.GlobalUnmarshal() instead. import ( "jsonface" "encoding/json" "fmt" "math" ) type ( Transporter interface { Transport(distance_km float64) (time_hours float64) } Bike struct{ NumGears int } Bus struct{ LineName string } Tesla struct{ Charge float64 } // Charge is a number between 0 and 1. ) func (me Bike) Transport(distance float64) (time float64) { // A Bike can go at least 8 km/h, and even faster with more gears: return distance / (8 + math.Sqrt(float64(me.NumGears))) } func (me Bus) Transport(distance float64) (time float64) { // Some bus lines are slower than others: var speed float64 switch me.LineName { case "7": speed = 10 case "185": speed = 12 default: panic(fmt.Errorf("Unknown Bus Line: %s", me.LineName)) } return distance / speed } func (me Tesla) Transport(distance float64) (time float64) { // A Tesla goes slower as it loses charge. // For simplicity of this example, the car does not lose charge during transportation. speed := 100 * me.Charge return distance / speed } func Transporter_UnmarshalJSON(bs []byte) (interface{}, error) { var data struct{ Type string } err := json.Unmarshal(bs, &data) if err != nil { return nil, err } switch data.Type { case "Bike": var bike Bike err := json.Unmarshal(bs, &bike) if err != nil { return nil, err } return bike, nil case "Bus": var bus Bus err := json.Unmarshal(bs, &bus) if err != nil { return nil, err } return bus, nil case "Tesla": var tesla Tesla err := json.Unmarshal(bs, &tesla) if err != nil { return nil, err } return tesla, nil default: return nil, fmt.Errorf("Unknown Transporter Type: %s", bs) } } func main() { var ts []Transporter bs := []byte(`[{ "Type":"Bike", "NumGears":9 }, { "Type":"Bus", "LineName":"7" }]`) cbmap := jsonface.CBMap{"jsonface_test.Transporter": Transporter_UnmarshalJSON} err := jsonface.Unmarshal(bs, &ts, cbmap) if err != nil { panic(err) } fmt.Printf("%#v\n", ts) }
Output: []jsonface_test.Transporter{jsonface_test.Bike{NumGears:9}, jsonface_test.Bus{LineName:"7"}}
Types ¶
type CB ¶
'CB' means 'Callback'. It is used for unmarshalling, with the same interface as an UnmarshalJSON method.
type CBMap ¶
CBMap is a TypeName-->CB mapping. It is used to tell the jsonface system which callbacks to use for which types.
type StuntDouble ¶
type StuntDouble string
StuntDouble is a type used internally within jsonface. Users of jsonface should ignore this type. It is an exported symbol (capitalized) for technical reasons -- the Go json unmarshaller requires destination types to be exported; an unexported symbol (lowercase) would not work. I apologize for the API noise.
func (StuntDouble) MarshalJSON ¶
func (me StuntDouble) MarshalJSON() ([]byte, error)
func (*StuntDouble) UnmarshalJSON ¶
func (me *StuntDouble) UnmarshalJSON(bs []byte) error
type TypeName ¶
type TypeName string
TypeName is the name of a type (usually prefixed by the package name). If you don't know the correct TypeName to use, try the GetTypeName() function.
func GetTypeName ¶
func GetTypeName(x interface{}) TypeName
GetTypeName can help you understand the correct TypeNames to use during development. After you understand how the TypeNames are made, you will usually just hard-code the names into your code, rather than using this function.
Coincidentally, this function produces the same result as fmt.Sprintf("%T",x) .
Example ¶
package main import ( "jsonface" "fmt" "os" ) type A int64 func main() { var i int64 fmt.Println("i:", jsonface.GetTypeName(i)) var a A fmt.Println("a:", jsonface.GetTypeName(a)) fmt.Println("&a:", jsonface.GetTypeName(&a)) fmt.Println("os.Stdout:", jsonface.GetTypeName(os.Stdout)) }
Output: i: int64 a: jsonface_test.A &a: *jsonface_test.A os.Stdout: *os.File