jsonface

package module
v0.0.0-...-95d9329 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 25, 2019 License: MIT Imports: 7 Imported by: 0

README

jsonface

Unmarshal JSON data into Go Interfaces

Installation: go get github.com/likebike/jsonface

Source Code: https://github.com/likebike/jsonface

API docs and usage examples: https://godoc.org/github.com/likebike/jsonface

About jsonface

jsonface 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.

Example

package main

import (
    "fmt"
    "encoding/json"

    "github.com/likebike/jsonface"
)

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
    }
)

func (me Bell)  Play() { fmt.Printf("Ding (%s Bell)\n", me.BellPitch) }
func (me Drum)  Play() { fmt.Printf("Boom (%f Drum)\n", me.DrumSize) }

func Instrument_UnmarshalJSON(bs []byte) (interface{},error) {
    var Keys map[string]interface{}
    err := json.Unmarshal(bs, &Keys); if err!=nil { return nil,err }

    if _,has:=Keys["BellPitch"]; has {
        var bell Bell
        err = json.Unmarshal(bs, &bell); if err!=nil { return nil,err }
        return bell,nil
    } else if _,has:=Keys["DrumSize"]; has {
        var drum Drum
        err = json.Unmarshal(bs, &drum); if err!=nil { return nil,err }
        return drum,nil
    } else {
        return nil,fmt.Errorf("Unknown Instument Type: %s",bs)
    }
}

// Register the callback with jsonface:
func init() {
    jsonface.AddGlobalCB("main.Instrument", Instrument_UnmarshalJSON)
}

func main() {
    bs := []byte(`{"Name":"Gabriella","Inst":{"BellPitch":"B♭"}}`)
    var bandmember BandMember
    err := jsonface.GlobalUnmarshal(bs,&bandmember); if err!=nil { panic(err) }
    fmt.Printf("bandmember=%#v\n",bandmember)

    // Output:
    // bandmember=main.BandMember{Name:"Gabriella", Inst:main.Bell{BellPitch:"B♭"}}
}

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

func AddGlobalCB(name TypeName, cb CB)

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

func GlobalUnmarshal(bs []byte, destPtr interface{}) error

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

func Unmarshal(bs []byte, destPtr interface{}, cbs CBMap) error

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

type CB func([]byte) (interface{}, error)

'CB' means 'Callback'. It is used for unmarshalling, with the same interface as an UnmarshalJSON method.

type CBMap

type CBMap map[TypeName]CB

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

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL