utils.json.go

 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
50
51
52
53
54
55
56
57
58
package main

import (
	"encoding/json"
	"fmt"
)

type StringOrArray []string

// UnmarshalJSON implements the json.Unmarshaler interface.
func (soa *StringOrArray) UnmarshalJSON(data []byte) error {
	var str string
	if err := json.Unmarshal(data, &str); err == nil {
		*soa = []string{str}
		return nil
	}

	var arr []string
	if err := json.Unmarshal(data, &arr); err != nil {
		return fmt.Errorf("failed to unmarshal to string or array of strings: %w", err)
	}

	*soa = arr
	return nil
}

type ContextElement struct {
	Simple  StringOrArray
	Complex map[string]string
}

// MarshalJSON implements the json.Unmarshaler interface.
func (ce *ContextElement) MarshalJSON() ([]byte, error) {
	if len(ce.Simple) > 0 {
		if len(ce.Simple) == 1 {
			return json.Marshal(ce.Simple[0])
		}
		return json.Marshal(ce.Simple)
	} else {
		return json.Marshal(ce.Complex)
	}
}

func (ce *ContextElement) UnmarshalJSON(data []byte) error {
	var str StringOrArray
	if err := json.Unmarshal(data, &str); err == nil {
		*ce = ContextElement{Simple: str}
		return err
	}

	var arr map[string]string
	if err := json.Unmarshal(data, &arr); err != nil {
		return fmt.Errorf("failed to unmarshal to string or array of strings: %w", err)
	}

	*ce = ContextElement{Complex: arr}
	return nil
}