Practical Reflection: Serializers
Building a simple JSON-like serializer with reflect
Custom JSON serializer overview
Building a custom serializer with reflection demonstrates practical reflection: iterate struct fields, read tags, access values, and build output — the same approach used by encoding/json internally.
Simple struct-to-map
Convert a struct to a map[string]any using reflection:
func StructToMap(v any) map[string]any {
t := reflect.TypeOf(v)
val := reflect.ValueOf(v)
result := make(map[string]any, t.NumField())
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if !f.IsExported() { continue }
key := f.Tag.Get("json")
if key == "" { key = f.Name }
result[key] = val.Field(i).Interface()
}
return result
}All lessons in this course
- reflect.Type and reflect.Value
- Inspecting Struct Fields and Tags
- Dynamic Function Calls
- Practical Reflection: Serializers