summaryrefslogtreecommitdiff
path: root/storageinfo.go
blob: 993f5ef2d36dc78dd9cb8c6194f8ad0f8767c770 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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
}
*/