Browse Source

serialize nil bug (invalid from value)

0x4a52466c696e74 2 months ago
parent
commit
bb69bd9e7c
2 changed files with 15 additions and 13 deletions
  1. 4 6
      serialize.go
  2. 11 7
      z_test.go

+ 4 - 6
serialize.go

@@ -34,6 +34,9 @@ func parseVal(from, to reflect.Value, fieldName string) IErrorArgs {
 
 
 func parseType(from, to reflect.Value, fieldName string) IErrorArgs {
 func parseType(from, to reflect.Value, fieldName string) IErrorArgs {
 	from = realValue(from)
 	from = realValue(from)
+	if !from.IsValid() {
+		return nil
+	}
 	to = realValue(to)
 	to = realValue(to)
 	tn := StructTypeName(to)
 	tn := StructTypeName(to)
 	cv, check := fieldConverters[tn]
 	cv, check := fieldConverters[tn]
@@ -70,6 +73,7 @@ func parseType(from, to reflect.Value, fieldName string) IErrorArgs {
 
 
 func realValue(val reflect.Value) reflect.Value {
 func realValue(val reflect.Value) reflect.Value {
 	if val.Kind() == reflect.Ptr || val.Kind() == reflect.Interface {
 	if val.Kind() == reflect.Ptr || val.Kind() == reflect.Interface {
+		//if val.Kind() == reflect.Interface {
 		if val.IsNil() && val.Kind() == reflect.Ptr {
 		if val.IsNil() && val.Kind() == reflect.Ptr {
 			val.Set(reflect.New(val.Type().Elem()))
 			val.Set(reflect.New(val.Type().Elem()))
 		}
 		}
@@ -143,12 +147,6 @@ loop:
 				rVal = from.FieldByName(fType.Name)
 				rVal = from.FieldByName(fType.Name)
 			}
 			}
 		case reflect.Map:
 		case reflect.Map:
-			/*
-				log.Println(fType.Name)
-				if rVal = from.MapIndex(reflect.ValueOf(strings.ToLower(fType.Name))); !rVal.IsValid() {
-					rVal = from.MapIndex(reflect.ValueOf(fType.Name))
-				}
-			*/
 			mapKeys := from.MapKeys()
 			mapKeys := from.MapKeys()
 			lowerFTypeName := strings.ToLower(fType.Name)
 			lowerFTypeName := strings.ToLower(fType.Name)
 			for _, key := range mapKeys {
 			for _, key := range mapKeys {

+ 11 - 7
z_test.go

@@ -396,9 +396,10 @@ func TestFieldNames(t *testing.T) {
 }
 }
 
 
 type User struct {
 type User struct {
-	ID      int
-	Name    string
-	Created time.Time
+	ID       int
+	Name     string
+	Created  time.Time
+	ParentID *int
 }
 }
 
 
 type AuthEmail struct {
 type AuthEmail struct {
@@ -433,9 +434,10 @@ func TestSerializeEmail(t *testing.T) {
 		"email":     "flint@77i.su",
 		"email":     "flint@77i.su",
 		"themeName": "th-name",
 		"themeName": "th-name",
 		"UUser": json.Map{
 		"UUser": json.Map{
-			"ID":      100,
-			"Name":    "User 100",
-			"Created": "10.11.1983 03:12K",
+			"ID":       100,
+			"Name":     "User 100",
+			"Created":  "10.11.1983 03:12",
+			"ParentID": nil,
 		},
 		},
 	}
 	}
 
 
@@ -446,5 +448,7 @@ func TestSerializeEmail(t *testing.T) {
 		t.Fatal(err)
 		t.Fatal(err)
 	}
 	}
 
 
-	t.Log(r, *r.UUser)
+	t.Log(r, *r.UUser, r.UUser.ParentID)
+	//t.Log(*r.UUser.ParentID)
+
 }
 }