Documentation
¶
Overview ¶
Package jsonpoly provides a way to unmarshal polymorphic JSON objects into a specific type based on a key. It uses reflection to determine the type of the object and to create a new instance of the unmarshalled object. The Container struct is a generic struct that can be used to unmarshal polymorphic JSON objects into a specific type based on a key. It is using the Helper interface to determine the type of the object and to create a new instance of the unmarshalled object. The Helper interface must be implemented by the user to provide the necessary methods to create and set the value of the object based on the key. The struct implementing this interface should be a pointer type and should contain public fields annotated with JSON tags that match the keys in the JSON object.
See the example package for usage.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrNotJSONObject = errors.New("not a JSON object")
ErrNotJSONObject is returned when the helper or value structs are not marshaled into a JSON object (i.e. the first and last byte are not '{' and '}').
Functions ¶
This section is empty.
Types ¶
type Container ¶
Container is a generic struct that can be used to unmarshal polymorphic JSON objects into a specific type based on a key. It is using the Helper interface to determine the type of the object and to create a new instance of the unmarshalled object.
Example (Marshal) ¶
dog := Dog{
XName: "Fido",
Breed: "Golden Retriever",
}
var c Container[Animal, *AnimalContainerHelper]
c.Value = dog
raw, err := json.Marshal(c)
if err != nil {
panic(err)
}
fmt.Println(string(raw))
Output: {"type":"dog","name":"Fido","breed":"Golden Retriever"}
Example (Unmarshal) ¶
raw := `{"type":"dog","name":"Fido","breed":"Golden Retriever"}`
var c Container[Animal, *AnimalContainerHelper]
err := json.Unmarshal([]byte(raw), &c)
if err != nil {
panic(err)
}
dog := c.Value.(Dog)
fmt.Printf("Type: %s\n", dog.Type())
fmt.Printf("Name: %s\n", dog.XName)
fmt.Printf("Breed: %s\n", dog.Breed)
Output: Type: dog Name: Fido Breed: Golden Retriever
func (Container[V, H]) MarshalJSON ¶
MarshalJSON marshals the Container struct into JSON bytes. It uses the helper struct to determine the type of the object and to attach the type information to the JSON bytes.
func (*Container[V, H]) UnmarshalJSON ¶
UnmarshalJSON unmarshals the raw JSON bytes into the Container struct. After unmarshalling, the Value field will contain the unmarshalled object. The helper struct is used to determine the type of the object and to create a new instance of the unmarshalled object.
type Helper ¶
type Helper[V any] interface { Get() V Set(value V) }
Helper is an interface that must be implemented by the user to provide the necessary methods to create and set the value of the object based on the key. The struct implementing this interface should be a pointer type and should contain public fields annotated with JSON tags that match the keys in the JSON object.