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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
// Package json provide functions for marshalling an unmarshalling types to JSON. These functions are meant to
// be utilized inside of structs that implement json.Unmarshaler and json.Marshaler interfaces.
// This package provides the additional functionality of writing fields that are not in the struct when marshalling
// to a field called AdditionalFields if that field exists and is a map[string]interface{}.
// When marshalling, if the struct has all the same prerequisites, it will uses the keys in AdditionalFields as
// extra fields. This package uses encoding/json underneath.
package json
import (
"bytes"
"encoding/json"
"fmt"
"reflect"
"strings"
)
const addField = "AdditionalFields"
const (
marshalJSON = "MarshalJSON"
unmarshalJSON = "UnmarshalJSON"
)
var (
leftBrace = []byte("{")[0]
rightBrace = []byte("}")[0]
comma = []byte(",")[0]
leftParen = []byte("[")[0]
rightParen = []byte("]")[0]
)
var mapStrInterType = reflect.TypeOf(map[string]interface{}{})
// stateFn defines a state machine function. This will be used in all state
// machines in this package.
type stateFn func() (stateFn, error)
// Marshal is used to marshal a type into its JSON representation. It
// wraps the stdlib calls in order to marshal a struct or *struct so
// that a field called "AdditionalFields" of type map[string]interface{}
// with "-" used inside struct tag `json:"-"` can be marshalled as if
// they were fields within the struct.
func Marshal(i interface{}) ([]byte, error) {
buff := bytes.Buffer{}
enc := json.NewEncoder(&buff)
enc.SetEscapeHTML(false)
enc.SetIndent("", "")
v := reflect.ValueOf(i)
if v.Kind() != reflect.Ptr && v.CanAddr() {
v = v.Addr()
}
err := marshalStruct(v, &buff, enc)
if err != nil {
return nil, err
}
return buff.Bytes(), nil
}
// Unmarshal unmarshals a []byte representing JSON into i, which must be a *struct. In addition, if the struct has
// a field called AdditionalFields of type map[string]interface{}, JSON data representing fields not in the struct
// will be written as key/value pairs to AdditionalFields.
func Unmarshal(b []byte, i interface{}) error {
if len(b) == 0 {
return nil
}
jdec := json.NewDecoder(bytes.NewBuffer(b))
jdec.UseNumber()
return unmarshalStruct(jdec, i)
}
// MarshalRaw marshals i into a json.RawMessage. If I cannot be marshalled,
// this will panic. This is exposed to help test AdditionalField values
// which are stored as json.RawMessage.
func MarshalRaw(i interface{}) json.RawMessage {
b, err := json.Marshal(i)
if err != nil {
panic(err)
}
return json.RawMessage(b)
}
// isDelim simply tests to see if a json.Token is a delimeter.
func isDelim(got json.Token) bool {
switch got.(type) {
case json.Delim:
return true
}
return false
}
// delimIs tests got to see if it is want.
func delimIs(got json.Token, want rune) bool {
switch v := got.(type) {
case json.Delim:
if v == json.Delim(want) {
return true
}
}
return false
}
// hasMarshalJSON will determine if the value or a pointer to this value has
// the MarshalJSON method.
func hasMarshalJSON(v reflect.Value) bool {
if method := v.MethodByName(marshalJSON); method.Kind() != reflect.Invalid {
_, ok := v.Interface().(json.Marshaler)
return ok
}
if v.Kind() == reflect.Ptr {
v = v.Elem()
} else {
if !v.CanAddr() {
return false
}
v = v.Addr()
}
if method := v.MethodByName(marshalJSON); method.Kind() != reflect.Invalid {
_, ok := v.Interface().(json.Marshaler)
return ok
}
return false
}
// callMarshalJSON will call MarshalJSON() method on the value or a pointer to this value.
// This will panic if the method is not defined.
func callMarshalJSON(v reflect.Value) ([]byte, error) {
if method := v.MethodByName(marshalJSON); method.Kind() != reflect.Invalid {
marsh := v.Interface().(json.Marshaler)
return marsh.MarshalJSON()
}
if v.Kind() == reflect.Ptr {
v = v.Elem()
} else {
if v.CanAddr() {
v = v.Addr()
}
}
if method := v.MethodByName(unmarshalJSON); method.Kind() != reflect.Invalid {
marsh := v.Interface().(json.Marshaler)
return marsh.MarshalJSON()
}
panic(fmt.Sprintf("callMarshalJSON called on type %T that does not have MarshalJSON defined", v.Interface()))
}
// hasUnmarshalJSON will determine if the value or a pointer to this value has
// the UnmarshalJSON method.
func hasUnmarshalJSON(v reflect.Value) bool {
// You can't unmarshal on a non-pointer type.
if v.Kind() != reflect.Ptr {
if !v.CanAddr() {
return false
}
v = v.Addr()
}
if method := v.MethodByName(unmarshalJSON); method.Kind() != reflect.Invalid {
_, ok := v.Interface().(json.Unmarshaler)
return ok
}
return false
}
// hasOmitEmpty indicates if the field has instructed us to not output
// the field if omitempty is set on the tag. tag is the string
// returned by reflect.StructField.Tag().Get().
func hasOmitEmpty(tag string) bool {
sl := strings.Split(tag, ",")
for _, str := range sl {
if str == "omitempty" {
return true
}
}
return false
}
|