a-h / generate

Generates Go (golang) Structs from JSON schema.
MIT License
444 stars 137 forks source link

structs with the same name #27

Closed the4thamigo-uk closed 6 years ago

the4thamigo-uk commented 7 years ago

It looks like object types defined with the same name in different parts of the schema do not appear as distinct structs in the rendered golang code. e.g.

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "x": {
      "type": "object",
      "properties": {
        "text": {
          "type": "string"
        }
      }
    },
    "y": {
      "type": "object",
      "properties": {
        "x": {
          "type": "object",
          "properties": {
            "number": {
              "type": "integer"
            }
          }
        }
      }
    },
    "z": {
      "type": "object",
      "properties": {
        "x" : {
          "type": "array",
          "items" : {
          "type": "object",
            "properties": {
              "float": {
                "type": "float"
              }
            }
          }      
        }
      }
    }
  }
}

Renders as

package main

type Root struct {
  X *X `json:"x,omitempty"`
  Y *Y `json:"y,omitempty"`
  Z *Z `json:"z,omitempty"`
}

type X struct {
  Float undefined `json:"float,omitempty"`
}

type Y struct {
  X *X `json:"x,omitempty"`
}

type Z struct {
  X []X `json:"x,omitempty"`
}
the4thamigo-uk commented 7 years ago

In my tentative fix for this, I had to add an extra public field to the Schema struct which is not ideal I admit. I dont see how to do this is a cleaner way without making some structural changes to the code. Any ideas?

Anyway the above json now renders as :

package main

// Root 
type Root struct {
  X *X `json:"x,omitempty"`
  Y *Y `json:"y,omitempty"`
  Z *Z `json:"z,omitempty"`
}

// X 
type X struct {
  Text string `json:"text,omitempty"`
}

// X2 
type X2 struct {
  Number int `json:"number,omitempty"`
}

// X3 
type X3 struct {
  Float undefined `json:"float,omitempty"`
}

// Y 
type Y struct {
  X *X2 `json:"x,omitempty"`
}

// Z 
type Z struct {
  X []X3 `json:"x,omitempty"`
}