SHARE
TWEET

Untitled

a guest Sep 17th, 2019 74 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package strarray
  2.  
  3. import (
  4.     "encoding/json"
  5.     "errors"
  6. )
  7.  
  8. var (
  9.     // ErrUnsupportedType is returned if the type is not implemented
  10.     ErrUnsupportedType = errors.New("unsupported type")
  11. )
  12.  
  13. // StrArray string array to be used on JSON UnmarshalJSON
  14. type StrArray []string
  15.  
  16. // UnmarshalJSON convert JSON object array of string or
  17. // a string format strings to a golang string array
  18. func (sa *StrArray) UnmarshalJSON(data []byte) error {
  19.     var jsonObj interface{}
  20.     err := json.Unmarshal(data, &jsonObj)
  21.     if err != nil {
  22.         return err
  23.     }
  24.     switch obj := jsonObj.(type) {
  25.     case string:
  26.         *sa = StrArray([]string{obj})
  27.         return nil
  28.     case []interface{}:
  29.         s := make([]string, 0, len(obj))
  30.         for _, v := range obj {
  31.             value, ok := v.(string)
  32.             if !ok {
  33.                 return ErrUnsupportedType
  34.             }
  35.             s = append(s, value)
  36.         }
  37.         *sa = StrArray(s)
  38.         return nil
  39.     }
  40.     return ErrUnsupportedType
  41. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top