0Pricing
Go Academy · Lesson

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

  1. reflect.Type and reflect.Value
  2. Inspecting Struct Fields and Tags
  3. Dynamic Function Calls
  4. Practical Reflection: Serializers
← Back to Go Academy