Ompluscator / dynamic-struct

Golang package for editing struct's fields during runtime and mapping structs to other structs.
MIT License
672 stars 83 forks source link

Support embedded dynamic struct #23

Closed leslie-qiwa closed 1 year ago

leslie-qiwa commented 2 years ago

Thanks for making this great tool. It is very useful for GraphQL query which requires dynamic struct sometimes.

One feature seems missing is not supported embedded dynamic struct. For example,

func main() {
  childStruct := dynamicstruct.NewStruct().
    AddField("Child", 0, `json:"int"`).
    Build()

  childInstance := childStruct.New()
  content, err := json.Marshal(childInstance)
  if err != nil {
    log.Fatal(err)
  }
  fmt.Println(string(content))

  parentStruct := dynamicstruct.NewStruct().
    AddField("Parent", &childInstance, "").Build()

  parentInstance := parentStruct.New()
  content, err = json.Marshal(parentInstance)
  if err != nil {
    log.Fatal(err)
  }

  fmt.Println(string(content))
}

Result will be:

{"int":0}
{"Parent":null}

Seems like this is due to embedded dynamic struct instance is not initialized, so if explicitly init like below, it will marshal correctly

func main() {
        childStruct := dynamicstruct.NewStruct().
                AddField("Child", 0, `json:"int"`).
                Build()

        childInstance := childStruct.New()
        content, err := json.Marshal(childInstance)
        if err != nil {
                log.Fatal(err)
        }
        fmt.Println(string(content))

        parentStruct := dynamicstruct.NewStruct().
                AddField("Parent", &childInstance, "").Build()

        parentInstance := parentStruct.New()

                data := []byte(`
                {
                        "Parent": {
                          "Child": 0
                        }
                }
                `)

                err = json.Unmarshal(data, &parentInstance)
                if err != nil {
                        log.Fatal(err)
                }

        content, err = json.Marshal(parentInstance)
        if err != nil {
                log.Fatal(err)
        }

        fmt.Println(string(content))
}

Marshal result is

{"int":0}
{"Parent":{"Child":0}}
mtt0 commented 2 years ago

See #21

PBholewasi commented 1 year ago

This is still not working