mirror of
https://github.com/emirpasic/gods.git
synced 2026-06-13 15:56:35 +03:00
14f714261f
* Generics migration This attempts to migrate this library in the least invasive way by preserving as much of the original API as possible. It does not change the tests in a meaningful way nor does it attempt to upgrade any logic that can be simplified or improved with generics. This is purely an API migration, and still requires a lot of additional work to be fully ready. * Fix a few broken tests around serialization * Add v2 suffix * Temporarily change mod name for testing * Rename module to /v2
53 lines
1.2 KiB
Go
53 lines
1.2 KiB
Go
package serialization
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"github.com/emirpasic/gods/v2/lists/arraylist"
|
|
"github.com/emirpasic/gods/v2/maps/hashmap"
|
|
)
|
|
|
|
// ListSerializationExample demonstrates how to serialize and deserialize lists to and from JSON
|
|
func ListSerializationExample() {
|
|
list := arraylist.New[string]()
|
|
list.Add("a", "b", "c")
|
|
|
|
// Serialization (marshalling)
|
|
json, err := list.ToJSON()
|
|
if err != nil {
|
|
fmt.Println(err)
|
|
}
|
|
fmt.Println(string(json)) // ["a","b","c"]
|
|
|
|
// Deserialization (unmarshalling)
|
|
json = []byte(`["a","b"]`)
|
|
err = list.FromJSON(json)
|
|
if err != nil {
|
|
fmt.Println(err)
|
|
}
|
|
fmt.Println(list) // ArrayList ["a","b"]
|
|
}
|
|
|
|
// MapSerializationExample demonstrates how to serialize and deserialize maps to and from JSON
|
|
func MapSerializationExample() {
|
|
m := hashmap.New[string, string]()
|
|
m.Put("a", "1")
|
|
m.Put("b", "2")
|
|
m.Put("c", "3")
|
|
|
|
// Serialization (marshalling)
|
|
json, err := m.ToJSON()
|
|
if err != nil {
|
|
fmt.Println(err)
|
|
}
|
|
fmt.Println(string(json)) // {"a":"1","b":"2","c":"3"}
|
|
|
|
// Deserialization (unmarshalling)
|
|
json = []byte(`{"a":"1","b":"2"}`)
|
|
err = m.FromJSON(json)
|
|
if err != nil {
|
|
fmt.Println(err)
|
|
}
|
|
fmt.Println(m) // HashMap {"a":"1","b":"2"}
|
|
}
|