From a1d53651c0ae4a14259f15b635a0a8a80778f447 Mon Sep 17 00:00:00 2001 From: Vadim Petrov Date: Wed, 3 May 2017 18:18:25 +0300 Subject: [PATCH] Handle embedded struct fields --- README.md | 11 ++++++++++- example/simple.go | 5 +++++ jsonschema.go | 12 ++++++++++++ jsonschema_test.go | 24 ++++++++++++++++++++++++ 4 files changed, 51 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index afda8a6..0dff428 100644 --- a/README.md +++ b/README.md @@ -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() { @@ -57,6 +62,9 @@ func main() { "Qux": { "type": "integer" }, + "Zoo": { + "type": "string" + }, "foo": { "type": "bool" } @@ -64,7 +72,8 @@ func main() { "required": [ "foo", "Qux", - "Baz" + "Baz", + "Zoo" ] } ``` diff --git a/example/simple.go b/example/simple.go index 4689fb7..0247e19 100644 --- a/example/simple.go +++ b/example/simple.go @@ -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() { diff --git a/jsonschema.go b/jsonschema.go index 0c68598..629c253 100644 --- a/jsonschema.go +++ b/jsonschema.go @@ -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) diff --git a/jsonschema_test.go b/jsonschema_test.go index 3ecfed8..9f6651c 100644 --- a/jsonschema_test.go +++ b/jsonschema_test.go @@ -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{}