...

Source file src/github.com/clbanning/mxj/v2/struct.go

Documentation: github.com/clbanning/mxj/v2

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

View as plain text