struct.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Copyright 2012-2017 Charles Banning. 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. package mxj
  5. import (
  6. "encoding/json"
  7. "errors"
  8. "reflect"
  9. // "github.com/fatih/structs"
  10. )
  11. // Create a new Map value from a structure. Error returned if argument is not a structure.
  12. // Only public structure fields are decoded in the Map value. See github.com/fatih/structs#Map
  13. // for handling of "structs" tags.
  14. // DEPRECATED - import github.com/fatih/structs and cast result of structs.Map to mxj.Map.
  15. // import "github.com/fatih/structs"
  16. // ...
  17. // sm, err := structs.Map(<some struct>)
  18. // if err != nil {
  19. // // handle error
  20. // }
  21. // m := mxj.Map(sm)
  22. // Alernatively uncomment the old source and import in struct.go.
  23. func NewMapStruct(structVal interface{}) (Map, error) {
  24. return nil, errors.New("deprecated - see package documentation")
  25. /*
  26. if !structs.IsStruct(structVal) {
  27. return nil, errors.New("NewMapStruct() error: argument is not type Struct")
  28. }
  29. return structs.Map(structVal), nil
  30. */
  31. }
  32. // Marshal a map[string]interface{} into a structure referenced by 'structPtr'. Error returned
  33. // if argument is not a pointer or if json.Unmarshal returns an error.
  34. // json.Unmarshal structure encoding rules are followed to encode public structure fields.
  35. func (mv Map) Struct(structPtr interface{}) error {
  36. // should check that we're getting a pointer.
  37. if reflect.ValueOf(structPtr).Kind() != reflect.Ptr {
  38. return errors.New("mv.Struct() error: argument is not type Ptr")
  39. }
  40. m := map[string]interface{}(mv)
  41. j, err := json.Marshal(m)
  42. if err != nil {
  43. return err
  44. }
  45. return json.Unmarshal(j, structPtr)
  46. }