50 lines
1.1 KiB
Go
50 lines
1.1 KiB
Go
package virtbuf
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"strconv"
|
|
)
|
|
|
|
// MarshalJSON custom marshals the StorageInfo struct to JSON
|
|
func (s StorageInfo) MarshalJSON() ([]byte, error) {
|
|
capacityStr := fmt.Sprintf("%d GB", s.Capacity)
|
|
return json.Marshal(map[string]string{
|
|
"capacity": capacityStr,
|
|
})
|
|
}
|
|
|
|
// UnmarshalJSON custom unmarshals JSON into the StorageInfo struct
|
|
func (s *StorageInfo) UnmarshalJSON(data []byte) error {
|
|
var raw map[string]string
|
|
if err := json.Unmarshal(data, &raw); err != nil {
|
|
return err
|
|
}
|
|
|
|
if capacityStr, ok := raw["capacity"]; ok {
|
|
capacityStr = capacityStr[:len(capacityStr)-3] // Remove the " GB" suffix
|
|
capacity, err := strconv.ParseInt(capacityStr, 10, 64)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
s.Capacity = capacity
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
/*
|
|
func main() {
|
|
info := StorageInfo{Capacity: 64}
|
|
|
|
// Marshaling to JSON
|
|
jsonData, _ := json.Marshal(info)
|
|
fmt.Println(string(jsonData)) // Output: {"capacity":"64 GB"}
|
|
|
|
// Unmarshaling back to Go struct
|
|
var newInfo StorageInfo
|
|
_ = json.Unmarshal(jsonData, &newInfo)
|
|
fmt.Println(newInfo.Capacity) // Output: 64
|
|
}
|
|
*/
|