github.com/TeaOSLab/EdgeNode@v1.3.8/internal/utils/jsonutils/map.go (about)

     1  // Copyright 2021 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
     2  
     3  package jsonutils
     4  
     5  import (
     6  	"encoding/json"
     7  	"github.com/iwind/TeaGo/maps"
     8  )
     9  
    10  func MapToObject(m maps.Map, ptr any) error {
    11  	if m == nil {
    12  		return nil
    13  	}
    14  	mJSON, err := json.Marshal(m)
    15  	if err != nil {
    16  		return err
    17  	}
    18  	return json.Unmarshal(mJSON, ptr)
    19  }
    20  
    21  func ObjectToMap(ptr any) (maps.Map, error) {
    22  	if ptr == nil {
    23  		return maps.Map{}, nil
    24  	}
    25  	ptrJSON, err := json.Marshal(ptr)
    26  	if err != nil {
    27  		return nil, err
    28  	}
    29  	var result = maps.Map{}
    30  	err = json.Unmarshal(ptrJSON, &result)
    31  	if err != nil {
    32  		return nil, err
    33  	}
    34  	return result, nil
    35  }
    36  
    37  func Copy(destPtr any, srcPtr any) error {
    38  	data, err := json.Marshal(srcPtr)
    39  	if err != nil {
    40  		return err
    41  	}
    42  	err = json.Unmarshal(data, destPtr)
    43  	return err
    44  }