code.cloudfoundry.org/cli@v7.1.0+incompatible/types/null_string.go (about)

     1  package types
     2  
     3  import (
     4  	"encoding/json"
     5  )
     6  
     7  type NullString struct {
     8  	Value string
     9  	IsSet bool
    10  }
    11  
    12  func NewNullString(optionalValue ...string) NullString {
    13  	switch len(optionalValue) {
    14  	case 0:
    15  		return NullString{IsSet: false}
    16  	case 1:
    17  		return NullString{Value: optionalValue[0], IsSet: true}
    18  	default:
    19  		panic("Too many strings passed to nullable string constructor")
    20  	}
    21  }
    22  
    23  func (n NullString) MarshalJSON() ([]byte, error) {
    24  	if n.IsSet {
    25  		return json.Marshal(n.Value)
    26  	}
    27  	return json.Marshal(nil)
    28  }
    29  
    30  func (n *NullString) UnmarshalJSON(rawJSON []byte) error {
    31  	var value *string
    32  	err := json.Unmarshal(rawJSON, &value)
    33  	if err != nil {
    34  		return err
    35  	}
    36  
    37  	if value == nil {
    38  		n.Value = ""
    39  		n.IsSet = false
    40  		return nil
    41  	}
    42  
    43  	n.Value = *value
    44  	n.IsSet = true
    45  
    46  	return nil
    47  }