github.com/arunkumar7540/cli@v6.45.0+incompatible/types/null_string.go (about)

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