Skip to content

v1.11.0

Compare
Choose a tag to compare
@wongoo wongoo released this 19 Jan 00:50
· 35 commits to 1.11 since this release

New Features

  • support encode object to map and vice versa. #309

The following example shows how that works:

person := Person{
	Age:      18,
	Sex:      true,
}

worker1 := &Worker{
	Person: person,
	CurJob: JOB{Title: "cto", Company: "facebook"},
	Jobs: []JOB{
		{Title: "manager", Company: "google"},
		{Title: "ceo", Company: "microsoft"},
	},
}

e := NewEncoder()
err := e.Encode(worker1)
if err != nil {
	t.Error(err)
	t.FailNow()
}
data := e.Buffer()

// unRegisterPOJO before decode, so that to decode to map
unRegisterPOJO(person)
unRegisterPOJO(worker1)
unRegisterPOJO(&worker1.Jobs[0])

// strict mode
d := NewDecoder(data)
d.Strict = true // set to strict mode, then the decoding will return error for class not being registered.
res, err := d.Decode()
if err == nil {
	t.Error("after unregister pojo, decoding should return error for strict mode")
	t.FailNow()
}

// non-strict mode, decode to map for class not being registered.
d = NewDecoder(data)
res, err = d.Decode()
if err != nil {
	t.Error(err)
	t.FailNow()
}

worker2, ok := res.(map[string]interface{}) // the response is a map
if !ok {
	t.Fatalf("res:%#v should be a map for non-strict mode", res)
}

// encode the map to object again, note the worker2 is a map.
e = NewEncoder()
err = e.Encode(worker2)
if err != nil {
	t.Error(err)
	t.FailNow()
}

data = e.Buffer()

// register pojo again, so that there are class definitions, which are used to encode map to object.
RegisterPOJO(person)
RegisterPOJO(worker1)
RegisterPOJO(&worker1.Jobs[0])

// decode the encoded map data to struct object.
d = NewDecoder(data)
res, err = d.Decode()
if err != nil {
	t.Error(err)
	t.FailNow()
}

worker3, ok := res.(*Worker) // worker3 is a Worker
if !ok {
	t.Fatalf("res:%#v should be a worker type", res)
}

if !reflect.DeepEqual(worker1, worker3) {
	t.Fatal("worker1 not equal to worker3!")
}