github.com/timstclair/heapster@v0.20.0-alpha1/Godeps/_workspace/src/google.golang.org/api/gensupport/json.go (about)

     1  // Copyright 2015 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package gensupport is an internal implementation detail used by code
     6  // generated by the google-api-go-generator tool.
     7  //
     8  // This package may be modified at any time without regard for backwards
     9  // compatibility. It should not be used directly by API users.
    10  package gensupport
    11  
    12  import (
    13  	"encoding/json"
    14  	"fmt"
    15  	"reflect"
    16  	"strings"
    17  )
    18  
    19  // MarshalJSON returns a JSON encoding of schema containing only selected fields.
    20  // A field is selected if:
    21  //   * it has a non-empty value, or
    22  //     * its field name is present in forceSendFields, and
    23  //     * it is not a nil pointer or nil interface.
    24  // The JSON key for each selected field is taken from the field's json: struct tag.
    25  func MarshalJSON(schema interface{}, forceSendFields []string) ([]byte, error) {
    26  	if len(forceSendFields) == 0 {
    27  		return json.Marshal(schema)
    28  	}
    29  
    30  	mustInclude := make(map[string]struct{})
    31  	for _, f := range forceSendFields {
    32  		mustInclude[f] = struct{}{}
    33  	}
    34  
    35  	dataMap, err := schemaToMap(schema, mustInclude)
    36  	if err != nil {
    37  		return nil, err
    38  	}
    39  	return json.Marshal(dataMap)
    40  }
    41  
    42  func schemaToMap(schema interface{}, mustInclude map[string]struct{}) (map[string]interface{}, error) {
    43  	m := make(map[string]interface{})
    44  	s := reflect.ValueOf(schema)
    45  	st := s.Type()
    46  
    47  	for i := 0; i < s.NumField(); i++ {
    48  		jsonTag := st.Field(i).Tag.Get("json")
    49  		if jsonTag == "" {
    50  			continue
    51  		}
    52  		tag, err := parseJSONTag(jsonTag)
    53  		if err != nil {
    54  			return nil, err
    55  		}
    56  		if tag.ignore {
    57  			continue
    58  		}
    59  
    60  		v := s.Field(i)
    61  		f := st.Field(i)
    62  		if !includeField(v, f, mustInclude) {
    63  			continue
    64  		}
    65  
    66  		// nil maps are treated as empty maps.
    67  		if f.Type.Kind() == reflect.Map && v.IsNil() {
    68  			m[tag.apiName] = map[string]string{}
    69  			continue
    70  		}
    71  
    72  		// nil slices are treated as empty slices.
    73  		if f.Type.Kind() == reflect.Slice && v.IsNil() {
    74  			m[tag.apiName] = []bool{}
    75  			continue
    76  		}
    77  
    78  		if tag.stringFormat {
    79  			m[tag.apiName] = formatAsString(v, f.Type.Kind())
    80  		} else {
    81  			m[tag.apiName] = v.Interface()
    82  		}
    83  	}
    84  	return m, nil
    85  }
    86  
    87  // formatAsString returns a string representation of v, dereferencing it first if possible.
    88  func formatAsString(v reflect.Value, kind reflect.Kind) string {
    89  	if kind == reflect.Ptr && !v.IsNil() {
    90  		v = v.Elem()
    91  	}
    92  
    93  	return fmt.Sprintf("%v", v.Interface())
    94  }
    95  
    96  // jsonTag represents a restricted version of the struct tag format used by encoding/json.
    97  // It is used to describe the JSON encoding of fields in a Schema struct.
    98  type jsonTag struct {
    99  	apiName      string
   100  	stringFormat bool
   101  	ignore       bool
   102  }
   103  
   104  // parseJSONTag parses a restricted version of the struct tag format used by encoding/json.
   105  // The format of the tag must match that generated by the Schema.writeSchemaStruct method
   106  // in the api generator.
   107  func parseJSONTag(val string) (jsonTag, error) {
   108  	if val == "-" {
   109  		return jsonTag{ignore: true}, nil
   110  	}
   111  
   112  	var tag jsonTag
   113  
   114  	i := strings.Index(val, ",")
   115  	if i == -1 || val[:i] == "" {
   116  		return tag, fmt.Errorf("malformed json tag: %s", val)
   117  	}
   118  
   119  	tag = jsonTag{
   120  		apiName: val[:i],
   121  	}
   122  
   123  	switch val[i+1:] {
   124  	case "omitempty":
   125  	case "omitempty,string":
   126  		tag.stringFormat = true
   127  	default:
   128  		return tag, fmt.Errorf("malformed json tag: %s", val)
   129  	}
   130  
   131  	return tag, nil
   132  }
   133  
   134  // Reports whether the struct field "f" with value "v" should be included in JSON output.
   135  func includeField(v reflect.Value, f reflect.StructField, mustInclude map[string]struct{}) bool {
   136  	// The regular JSON encoding of a nil pointer is "null", which means "delete this field".
   137  	// Therefore, we could enable field deletion by honoring pointer fields' presence in the mustInclude set.
   138  	// However, many fields are not pointers, so there would be no way to delete these fields.
   139  	// Rather than partially supporting field deletion, we ignore mustInclude for nil pointer fields.
   140  	// Deletion will be handled by a separate mechanism.
   141  	if f.Type.Kind() == reflect.Ptr && v.IsNil() {
   142  		return false
   143  	}
   144  
   145  	// The "any" type is represented as an interface{}.  If this interface
   146  	// is nil, there is no reasonable representation to send.  We ignore
   147  	// these fields, for the same reasons as given above for pointers.
   148  	if f.Type.Kind() == reflect.Interface && v.IsNil() {
   149  		return false
   150  	}
   151  
   152  	_, ok := mustInclude[f.Name]
   153  	return ok || !isEmptyValue(v)
   154  }
   155  
   156  // isEmptyValue reports whether v is the empty value for its type.  This
   157  // implementation is based on that of the encoding/json package, but its
   158  // correctness does not depend on it being identical. What's important is that
   159  // this function return false in situations where v should not be sent as part
   160  // of a PATCH operation.
   161  func isEmptyValue(v reflect.Value) bool {
   162  	switch v.Kind() {
   163  	case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
   164  		return v.Len() == 0
   165  	case reflect.Bool:
   166  		return !v.Bool()
   167  	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
   168  		return v.Int() == 0
   169  	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
   170  		return v.Uint() == 0
   171  	case reflect.Float32, reflect.Float64:
   172  		return v.Float() == 0
   173  	case reflect.Interface, reflect.Ptr:
   174  		return v.IsNil()
   175  	}
   176  	return false
   177  }