Skip to content

Commit 34c2229

Browse files
committed
update with different approach
1 parent 2e539ed commit 34c2229

File tree

2 files changed

+34
-3
lines changed

2 files changed

+34
-3
lines changed

openapi2/issues1010_test.go

+1
Original file line numberDiff line numberDiff line change
@@ -94,4 +94,5 @@ func TestIssue1010(t *testing.T) {
9494
var doc2 T
9595
err := json.Unmarshal(v2, &doc2)
9696
require.NoError(t, err)
97+
require.Equal(t, "petType", doc2.Definitions["Pet"].Value.Discriminator.PropertyName)
9798
}

openapi3/schema.go

+33-3
Original file line numberDiff line numberDiff line change
@@ -404,12 +404,42 @@ func (schema Schema) MarshalYAML() (any, error) {
404404

405405
// UnmarshalJSON sets Schema to a copy of data.
406406
func (schema *Schema) UnmarshalJSON(data []byte) error {
407-
type SchemaBis Schema
407+
type Alias Schema
408+
type SchemaBis struct {
409+
Alias
410+
Discriminator json.RawMessage `json:"discriminator,omitempty"`
411+
}
412+
408413
var x SchemaBis
409414
if err := json.Unmarshal(data, &x); err != nil {
410415
return unmarshalError(err)
411416
}
412-
_ = json.Unmarshal(data, &x.Extensions)
417+
418+
type DiscriminatorObject struct {
419+
Discriminator *Discriminator `json:"discriminator,omitempty" yaml:"discriminator,omitempty"`
420+
}
421+
422+
if len(x.Discriminator) > 0 {
423+
// Attempt to unmarshal as a pointer to a string first
424+
var ds *string
425+
if err := json.Unmarshal(x.Discriminator, &ds); err == nil {
426+
// If it's a non-nil string pointer, assign it to PropertyName
427+
if ds != nil {
428+
x.Alias.Discriminator = &Discriminator{
429+
PropertyName: *ds,
430+
}
431+
}
432+
} else {
433+
// If it's not a string, try to unmarshal as an object
434+
var do DiscriminatorObject
435+
if err := json.Unmarshal(x.Discriminator, &do.Discriminator); err == nil && do.Discriminator != nil {
436+
// Assign the object if unmarshaling is successful
437+
x.Alias.Discriminator = do.Discriminator
438+
}
439+
}
440+
}
441+
442+
_ = json.Unmarshal(data, &x.Alias.Extensions)
413443

414444
delete(x.Extensions, "oneOf")
415445
delete(x.Extensions, "anyOf")
@@ -464,7 +494,7 @@ func (schema *Schema) UnmarshalJSON(data []byte) error {
464494
x.Extensions = nil
465495
}
466496

467-
*schema = Schema(x)
497+
*schema = Schema(x.Alias)
468498

469499
if schema.Format == "date" {
470500
// This is a fix for: https://github.com/getkin/kin-openapi/issues/697

0 commit comments

Comments
 (0)