package main import ( "fmt" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" ) type MyCustomObject struct { Name string Age int } var ( GroupVersion = schema.GroupVersion{ Group: "mygroup.example.com", Version: "v1alpha1", } ) func main() { scheme := runtime.NewScheme() scheme.AddKnownTypes(GroupVersion, &MyCustomObject{}, ) obj, err := scheme.New(GroupVersion.WithKind("MyCustomObject")) if err != nil { panic(err) } myObj, ok := obj.(*MyCustomObject) if !ok { panic("unexpected type") } myObj.Name = "John" myObj.Age = 30 fmt.Printf("%+v\n", myObj) }
package main import ( "encoding/json" "fmt" "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" ) type MyCustomObject struct { Name string Age int } var ( GroupVersion = schema.GroupVersion{ Group: "mygroup.example.com", Version: "v1alpha1", } ) func main() { scheme := runtime.NewScheme() scheme.AddKnownTypes(GroupVersion, &MyCustomObject{}, ) myObj := MyCustomObject{Name: "John", Age: 30} serialized, err := json.Marshal(&myObj) if err != nil { panic(err) } obj, err := runtime.Decode(scheme, serialized) if err != nil { panic(err) } myObjFromScheme, ok := obj.(*MyCustomObject) if !ok { panic("unexpected type") } fmt.Printf("%+v\n", myObjFromScheme) metaObj, err := runtime.GetObjectMeta(myObjFromScheme) if err != nil { panic(err) } fmt.Printf("%+v\n", metaObj) }This example demonstrates how to marshal a custom API object, `MyCustomObject`, to JSON and then unmarshal it back to an object using the Scheme's `Decode` function. We also use the Scheme's `GetObjectMeta` function to retrieve metadata information about the object from the Scheme.