clbanning/mxj

Got `UNKNOWN` error when encoding custom type of slice

gqcn opened this issue · 2 comments

gqcn commented
package main

import (
	"fmt"
	"github.com/clbanning/mxj"
)

type (
	MyMap   map[string]interface{}
	MySlice []interface{}
)

func main() {
	m := MyMap{
		"a": "aaa",
		"b": MyMap{
			"c": MySlice{
				MyMap{"tt": "t1"},
				MyMap{"tt": "t2"},
				MyMap{"tt": "t3"},
			},
		},
	}
	b, err := mxj.Map(m).Xml("Abc")
	if err != nil {
		panic(err)
	}
	fmt.Println(string(b))

}

Expect:

<Abc><a>aaa</a><b><c><tt>t1</tt></c><c><tt>t2</tt></c><c><tt>t3</tt></c></b></Abc>

But Got:

<Abc><a>aaa</a><b><c>>UNKNOWN/></b></Abc>

Don't know what version of package you're using; at tip I'm getting:

<Abc><a>aaa</a><b><c>[map[tt:t1] map[tt:t2] map[tt:t3]]</c></b></Abc>

which is meaningless, also.

Will look into it when I get some time later today or this weekend.

Here's the problem - the mxi package can only work with go types. When you define a type, e.g. MyMap, it is not visible to the mxj package; so it doesn't know how to coerce it to map[string]interface{}. This is because clbanning/mxj DOES NOT IMPORT the type definition; thus, clbanning/mxj is only aware of types that are defined in the package or are standard go types.

This works.

package main

import (
	"fmt"
	"github.com/clbanning/mxj"
)

// type (
// 	MyMap   map[string]interface{}
// 	MySlice []interface{}
// )

func main() {
	m := map[string]interface{}{
		"a": "aaa",
		"b": map[string]interface{}{
			"c": []interface{}{
				map[string]interface{}{"tt": "t1"},
				map[string]interface{}{"tt": "t2"},
				map[string]interface{}{"tt": "t3"},
			},
		},
	}
	b, err := mxj.Map(m).Xml("Abc")
	if err != nil {
		panic(err)
	}
	fmt.Println(string(b))

}

The result is -

<Abc><a>aaa</a><b><c><tt>t1</tt></c><c><tt>t2</tt></c><c><tt>t3</tt></c></b></Abc>