|
|
|
@@ -77,20 +77,31 @@ func (m *RWMap[K, V]) Len() int { |
|
|
|
func LoadFromJsonString[K comparable, V any](m *RWMap[K, V], jsonStr string) error { |
|
|
|
m.mutex.Lock() |
|
|
|
defer m.mutex.Unlock() |
|
|
|
m.data = make(map[K]V) |
|
|
|
return common.Unmarshal([]byte(jsonStr), &m.data) |
|
|
|
// 先尝试解析到临时 map,成功后再替换,避免解析失败时丢失原有数据 |
|
|
|
tempData := make(map[K]V) |
|
|
|
err := common.Unmarshal([]byte(jsonStr), &tempData) |
|
|
|
if err != nil { |
|
|
|
return err |
|
|
|
} |
|
|
|
m.data = tempData |
|
|
|
return nil |
|
|
|
} |
|
|
|
|
|
|
|
// LoadFromJsonStringWithCallback loads a JSON string into the RWMap and calls the callback on success. |
|
|
|
func LoadFromJsonStringWithCallback[K comparable, V any](m *RWMap[K, V], jsonStr string, onSuccess func()) error { |
|
|
|
m.mutex.Lock() |
|
|
|
defer m.mutex.Unlock() |
|
|
|
m.data = make(map[K]V) |
|
|
|
err := common.Unmarshal([]byte(jsonStr), &m.data) |
|
|
|
if err == nil && onSuccess != nil { |
|
|
|
// 先尝试解析到临时 map,成功后再替换,避免解析失败时丢失原有数据 |
|
|
|
tempData := make(map[K]V) |
|
|
|
err := common.Unmarshal([]byte(jsonStr), &tempData) |
|
|
|
if err != nil { |
|
|
|
return err |
|
|
|
} |
|
|
|
m.data = tempData |
|
|
|
if onSuccess != nil { |
|
|
|
onSuccess() |
|
|
|
} |
|
|
|
return err |
|
|
|
return nil |
|
|
|
} |
|
|
|
|
|
|
|
// MarshalJSONString returns the JSON string representation of the RWMap. |
|
|
|
|