example_test.go (913B)
1 package emarshal 2 3 import ( 4 "fmt" 5 "encoding/json" 6 ) 7 8 type A struct { 9 A string 10 } 11 12 func (a A) EMarshalA() (any, error) { 13 return a, nil 14 } 15 16 func (a *A) EUnmarshalA(unpack Unpack) error { 17 a.A = "hello" 18 return nil 19 } 20 21 type B struct { 22 B string 23 } 24 25 func (b B) EMarshalB() (any, error) { 26 return b, nil 27 } 28 29 func (b *B) EUnmarshalB(unpack Unpack) error { 30 return unpack(b) 31 } 32 33 type C struct { 34 A 35 B 36 } 37 38 func (c C) MarshalJSON() ([]byte, error) { 39 return Marshal(c, json.Marshal) 40 } 41 42 func (c *C) UnmarshalJSON(b []byte) error { 43 return Unmarshal(c, b, json.Unmarshal) 44 } 45 46 func Example() { 47 from := C{ 48 A: A{"hi"}, 49 B: B{"bye"}, 50 } 51 52 jsontxt, err := json.MarshalIndent(from, "", " ") 53 fmt.Printf("%s\n%+v\n", jsontxt, err) 54 55 var to C 56 57 err = json.Unmarshal(jsontxt, &to) 58 fmt.Printf("%+v\n%+v\n", to, err) 59 60 // Unordered output: 61 // { 62 // "A": "hi", 63 // "B": "bye" 64 // } 65 // <nil> 66 // {A:{A:hello} B:{B:bye}} 67 // <nil> 68 }