goext/sq/json.go
Mike Schwörer 9e5b8c5277
All checks were successful
Build Docker and Deploy / Run goext test-suite (push) Successful in 1m25s
v0.0.399 added sq.NewAutoDBTypeConverter
2024-03-09 14:16:35 +01:00

60 lines
1.2 KiB
Go

package sq
import "encoding/json"
type JsonObj map[string]any
func (j JsonObj) MarshalToDB(v JsonObj) (string, error) {
mrsh, err := json.Marshal(v)
if err != nil {
return "", err
}
return string(mrsh), nil
}
func (j JsonObj) UnmarshalToModel(v string) (JsonObj, error) {
var mrsh JsonObj
if err := json.Unmarshal([]byte(v), &mrsh); err != nil {
return JsonObj{}, err
}
return mrsh, nil
}
type JsonArr []any
func (j JsonArr) MarshalToDB(v JsonArr) (string, error) {
mrsh, err := json.Marshal(v)
if err != nil {
return "", err
}
return string(mrsh), nil
}
func (j JsonArr) UnmarshalToModel(v string) (JsonArr, error) {
var mrsh JsonArr
if err := json.Unmarshal([]byte(v), &mrsh); err != nil {
return JsonArr{}, err
}
return mrsh, nil
}
type AutoJson[T any] struct {
Value T
}
func (j AutoJson[T]) MarshalToDB(v AutoJson[T]) (string, error) {
mrsh, err := json.Marshal(v.Value)
if err != nil {
return "", err
}
return string(mrsh), nil
}
func (j AutoJson[T]) UnmarshalToModel(v string) (AutoJson[T], error) {
mrsh := *new(T)
if err := json.Unmarshal([]byte(v), &mrsh); err != nil {
return AutoJson[T]{}, err
}
return AutoJson[T]{Value: mrsh}, nil
}