github.com/mymmsc/gox@v1.3.33/util/examples/serialization/serialization.go (about) 1 package serialization 2 3 import ( 4 "fmt" 5 "github.com/mymmsc/gox/util/arraylist" 6 "github.com/mymmsc/gox/util/hashmap" 7 ) 8 9 // ListSerializationExample demonstrates how to serialize and deserialize lists to and from JSON 10 func ListSerializationExample() { 11 list := arraylist.New() 12 list.Add("a", "b", "c") 13 14 // Serialization (marshalling) 15 json, err := list.ToJSON() 16 if err != nil { 17 fmt.Println(err) 18 } 19 fmt.Println(string(json)) // ["a","b","c"] 20 21 // Deserialization (unmarshalling) 22 json = []byte(`["a","b"]`) 23 err = list.FromJSON(json) 24 if err != nil { 25 fmt.Println(err) 26 } 27 fmt.Println(list) // ArrayList ["a","b"] 28 } 29 30 // MapSerializationExample demonstrates how to serialize and deserialize maps to and from JSON 31 func MapSerializationExample() { 32 m := hashmap.New() 33 m.Put("a", "1") 34 m.Put("b", "2") 35 m.Put("c", "3") 36 37 // Serialization (marshalling) 38 json, err := m.ToJSON() 39 if err != nil { 40 fmt.Println(err) 41 } 42 fmt.Println(string(json)) // {"a":"1","b":"2","c":"3"} 43 44 // Deserialization (unmarshalling) 45 json = []byte(`{"a":"1","b":"2"}`) 46 err = m.FromJSON(json) 47 if err != nil { 48 fmt.Println(err) 49 } 50 fmt.Println(m) // HashMap {"a":"1","b":"2"} 51 }