Skip to content

Commit

Permalink
Handle embedded struct fields
Browse files Browse the repository at this point in the history
  • Loading branch information
Vadim Petrov committed May 3, 2017
1 parent b230f13 commit a1d5365
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 1 deletion.
11 changes: 10 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,16 @@ import (
"github.com/mcuadros/go-jsonschema-generator"
)

type EmbeddedType struct {
Zoo string
}

type ExampleBasic struct {
Foo bool `json:"foo"`
Bar string `json:",omitempty"`
Qux int8
Baz []string
EmbeddedType
}

func main() {
Expand All @@ -57,14 +62,18 @@ func main() {
"Qux": {
"type": "integer"
},
"Zoo": {
"type": "string"
},
"foo": {
"type": "bool"
}
},
"required": [
"foo",
"Qux",
"Baz"
"Baz",
"Zoo"
]
}
```
Expand Down
5 changes: 5 additions & 0 deletions example/simple.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,16 @@ import (
"github.com/mcuadros/go-jsonschema-generator"
)

type EmbeddedType struct {
Zoo string
}

type ExampleBasic struct {
Foo bool `json:"foo"`
Bar string `json:",omitempty"`
Qux int8
Baz []string
EmbeddedType
}

func main() {
Expand Down
12 changes: 12 additions & 0 deletions jsonschema.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,18 @@ func (p *property) readFromStruct(t reflect.Type) {
continue
}

if field.Anonymous {
embeddedProperty := &property{}
embeddedProperty.read(field.Type, opts)

for name, property := range embeddedProperty.Properties {
p.Properties[name] = property
}
p.Required = append(p.Required, embeddedProperty.Required...)

continue
}

p.Properties[name] = &property{}
p.Properties[name].read(field.Type, opts)

Expand Down
24 changes: 24 additions & 0 deletions jsonschema_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,30 @@ func (self *propertySuite) TestLoadNested(c *C) {
})
}

type EmbeddedStruct struct {
Foo string
}

type ExampleJSONEmbeddedStruct struct {
EmbeddedStruct
}

func (self *propertySuite) TestLoadEmbedded(c *C) {
j := &Document{}
j.Read(&ExampleJSONEmbeddedStruct{})

c.Assert(*j, DeepEquals, Document{
Schema: "http://json-schema.org/schema#",
property: property{
Type: "object",
Properties: map[string]*property{
"Foo": &property{Type: "string"},
},
Required: []string{"Foo"},
},
})
}

type ExampleJSONBasicMaps struct {
Maps map[string]string `json:",omitempty"`
MapOfInterface map[string]interface{}
Expand Down

0 comments on commit a1d5365

Please sign in to comment.