54 lines
1.2 KiB
Go
54 lines
1.2 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,
|
|
})
|
|
}
|
|
|
|
func (s StorageInfo) FormatJSON() string {
|
|
return fmt.Sprintf("\"capacity\": \"%d GB\"", s.Capacity)
|
|
}
|
|
|
|
// 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
|
|
}
|
|
*/
|