Ver código fonte

fix struct with one pointer field

Tao Wen 8 anos atrás
pai
commit
a92111261c
2 arquivos alterados com 19 adições e 0 exclusões
  1. 4 0
      feature_reflect_object.go
  2. 15 0
      jsoniter_reflect_struct_test.go

+ 4 - 0
feature_reflect_object.go

@@ -51,6 +51,10 @@ func encoderOfStruct(typ reflect.Type) (Encoder, error) {
 			if field.Type.Kind() == reflect.Map && typ.NumField() > 1 {
 				encoder = &optionalEncoder{encoder}
 			}
+			// one field pointer field will be inlined
+			if field.Type.Kind() == reflect.Ptr && typ.NumField() == 1 {
+				encoder = (encoder.(*optionalEncoder)).valueEncoder
+			}
 		}
 		for _, fieldName := range fieldNames {
 			structEncoder_.fields = append(structEncoder_.fields,

+ 15 - 0
jsoniter_reflect_struct_test.go

@@ -200,3 +200,18 @@ func Test_recursive_struct(t *testing.T) {
 	err = UnmarshalFromString(str, &obj)
 	should.Nil(err)
 }
+
+func Test_one_field_struct(t *testing.T) {
+	should := require.New(t)
+	type AnotherObject struct {
+	}
+	type TestObject struct {
+		Me *AnotherObject
+	}
+	obj := TestObject{}
+	str, err := MarshalToString(obj)
+	should.Nil(err)
+	should.Equal(`{"Me":{}}`, str)
+	err = UnmarshalFromString(str, &obj)
+	should.Nil(err)
+}