blob: 9056397fa5170f9743499f5c358c4c286430aace [file] [log] [blame]
Scott Bakere7144bc2019-10-01 14:16:47 -07001/*
2Copyright 2014 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package runtime
18
19import (
20 "bytes"
21 "encoding/json"
22 "errors"
23)
24
25func (re *RawExtension) UnmarshalJSON(in []byte) error {
26 if re == nil {
27 return errors.New("runtime.RawExtension: UnmarshalJSON on nil pointer")
28 }
29 if !bytes.Equal(in, []byte("null")) {
30 re.Raw = append(re.Raw[0:0], in...)
31 }
32 return nil
33}
34
35// MarshalJSON may get called on pointers or values, so implement MarshalJSON on value.
36// http://stackoverflow.com/questions/21390979/custom-marshaljson-never-gets-called-in-go
37func (re RawExtension) MarshalJSON() ([]byte, error) {
38 if re.Raw == nil {
39 // TODO: this is to support legacy behavior of JSONPrinter and YAMLPrinter, which
40 // expect to call json.Marshal on arbitrary versioned objects (even those not in
41 // the scheme). pkg/kubectl/resource#AsVersionedObjects and its interaction with
42 // kubectl get on objects not in the scheme needs to be updated to ensure that the
43 // objects that are not part of the scheme are correctly put into the right form.
44 if re.Object != nil {
45 return json.Marshal(re.Object)
46 }
47 return []byte("null"), nil
48 }
49 // TODO: Check whether ContentType is actually JSON before returning it.
50 return re.Raw, nil
51}