struct.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. // Copyright 2012-2014 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. "github.com/fatih/structs"
  9. "reflect"
  10. )
  11. // Create a new Map value from a structure. Error returned if argument is not a structure
  12. // or if there is a json.Marshal or json.Unmarshal error.
  13. // Only public structure fields are decoded in the Map value. Also, json.Marshal structure encoding rules
  14. // are followed for decoding the structure fields.
  15. func NewMapStruct(structVal interface{}) (Map, error) {
  16. if !structs.IsStruct(structVal) {
  17. return nil, errors.New("NewMapStruct() error: argument is not type Struct")
  18. }
  19. return structs.Map(structVal), nil
  20. }
  21. // Marshal a map[string]interface{} into a structure referenced by 'structPtr'. Error returned
  22. // if argument is not a pointer or if json.Unmarshal returns an error.
  23. // json.Unmarshal structure encoding rules are followed to encode public structure fields.
  24. func (mv Map) Struct(structPtr interface{}) error {
  25. // should check that we're getting a pointer.
  26. if reflect.ValueOf(structPtr).Kind() != reflect.Ptr {
  27. return errors.New("mv.Struct() error: argument is not type Ptr")
  28. }
  29. m := map[string]interface{}(mv)
  30. j, err := json.Marshal(m)
  31. if err != nil {
  32. return err
  33. }
  34. return json.Unmarshal(j, structPtr)
  35. }