-
Notifications
You must be signed in to change notification settings - Fork 16
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
c7622db
commit 7e93539
Showing
2 changed files
with
38 additions
and
37 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,37 +1,38 @@ | ||
package types | ||
|
||
import "encoding/json" | ||
import ( | ||
"encoding/json" | ||
"reflect" | ||
) | ||
|
||
type ArrayOKfloat64 struct { | ||
Value float64 | ||
Array []float64 | ||
type ArrayOK[T any] struct { | ||
Value T | ||
Array []T | ||
} | ||
|
||
func (arrayOK *ArrayOKfloat64) MarshalJSON() ([]byte, error) { | ||
if arrayOK.Array != nil { | ||
return json.Marshal(arrayOK.Array) | ||
} | ||
return json.Marshal(arrayOK.Value) | ||
func (arrayOK *ArrayOK[T]) MarshalJSON() ([]byte, error) { | ||
if arrayOK.Array!= nil { | ||
return json.Marshal(arrayOK.Array) | ||
} | ||
return json.Marshal(arrayOK.Value) | ||
} | ||
|
||
func (arrayOK *ArrayOKfloat64) UnmarshalJSON(data []byte) error { | ||
arrayOK.Array = nil | ||
arrayOK.Value = 0 | ||
func (arrayOK *ArrayOK[T]) UnmarshalJSON(data []byte) error { | ||
arrayOK.Array = nil | ||
arrayOK.Value = reflect.Zero(reflect.TypeOf(arrayOK.Value)).Interface().(T) | ||
|
||
var array []float64 | ||
err := json.Unmarshal(data, &array) | ||
if err == nil { | ||
arrayOK.Array = array | ||
return nil | ||
} | ||
var array []T | ||
err := json.Unmarshal(data, &array) | ||
if err == nil { | ||
arrayOK.Array = array | ||
return nil | ||
} | ||
|
||
var value float64 | ||
err = json.Unmarshal(data, &value) | ||
if err != nil { | ||
return err | ||
} | ||
arrayOK.Value = value | ||
return nil | ||
return nil | ||
|
||
} | ||
var value T | ||
err = json.Unmarshal(data, &value) | ||
if err!= nil { | ||
return err | ||
} | ||
arrayOK.Value = value | ||
return nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters