docs: update jsonUtil remark (#48)

This commit is contained in:
jefferyjob
2023-06-02 17:10:12 +08:00
committed by GitHub
parent 869aab1000
commit 3c0b974746
2 changed files with 49 additions and 27 deletions

View File

@@ -17,10 +17,32 @@ var (
ErrNotSlice = errors.New("cannot parse slice, value is not a slice")
)
// JsonToStruct Parses JSON into a specified structure pointer
// 将JSON解析为指定的结构体指针
func JsonToStruct(jsonData string, result any) error {
if reflect.ValueOf(result).Kind() != reflect.Pointer || reflect.ValueOf(result).IsNil() {
// JsonToStruct converts JSON data to a Go structure.
// Parameters:
//
// jsonData: A string containing the JSON data.
// val: A pointer to the structure variable to be filled.
//
// Returns:
//
// error: If conversion fails or an error occurs, the corresponding error is returned. If successful, nil is returned.
//
// Functionality:
//
// Checks if the val parameter is a non-nil pointer type, returning ErrPoint if it is not.
// Parses jsonData into a map[string]any variable called data.
// Retrieves the value and type of the structure pointed to by val using reflection.
// Iterates through the fields of the structure:
// Retrieves the field's type, name, and value.
// Gets the JSON tag for the field.
// Performs the appropriate handling if a key-value pair corresponding to the JSON tag exists in data:
// If the field is a primitive type (string, integer, float, boolean), parses it into the corresponding type's value.
// If the field is a struct type, recursively calls the JsonToStruct function to convert the sub-structure to JSON.
// If the field is a map type, uses the parseMap function to convert the sub-map to JSON.
// If the field is a slice type, uses the parseSlice function to convert the sub-slice to JSON.
// If the field is an interface type, sets the value to nil or the corresponding value.
func JsonToStruct(jsonData string, val any) error {
if reflect.ValueOf(val).Kind() != reflect.Pointer || reflect.ValueOf(val).IsNil() {
return ErrPoint
}
@@ -30,7 +52,7 @@ func JsonToStruct(jsonData string, result any) error {
return err
}
resultValue := reflect.ValueOf(result).Elem()
resultValue := reflect.ValueOf(val).Elem()
resultType := resultValue.Type()
for i := 0; i < resultType.NumField(); i++ {