-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathany.go
50 lines (45 loc) · 1.6 KB
/
any.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
package geko
import "encoding/json"
// Any is a wrapper for an any value. But when unmarshal, it uses our
// [Object]/[ObjectItems] and [Array] when meet JSON object and array.
//
// So the type of Any.Value after a [json.Unmarshal] can be:
// bool, float64/[json.Number], string, nil,
// [Object]/[ObjectItems], [Array].
//
// You can customize the unmarshal behavior by setting Any.Opts before call
// [json.Unmarshal]. Usually you don't need to use this type directly,
// `JSONUnmarshal` convenience function is more easy to use.
//
// And, do not use
// this type on the value type parameter of the [Map], [Pairs] or [List].
// Because container types already handles standard any type specially,
// doing so will not only has no benefit, but also lose performance.
type Any struct {
Value any
Opts DecodeOptions
}
// MarshalJSON implements [json.Marshaler] interface.
//
// You should not call this directly, use [json.Marshal] instead.
func (v Any) MarshalJSON() ([]byte, error) {
return json.Marshal(v.Value)
}
// UnmarshalJSON implements [json.Unmarshaler] interface.
//
// You shouldn't call this directly, use [json.Unmarshal]/[JSONUnmarshal]
// instead.
func (v *Any) UnmarshalJSON(data []byte) error {
value, err := newDecoder(data, v.Opts).decode()
if err == nil {
v.Value = value
}
return err
}
// JSONUnmarshal is A convenience function for unmarshal JSON data into an
// [Any] and get the inner any value, with provided option applied.
func JSONUnmarshal(data []byte, option ...DecodeOption) (any, error) {
a := Any{Opts: CreateDecodeOptions(option...)}
err := json.Unmarshal(data, &a)
return a.Value, err
}