I want to decode a request JSON that the value of a field could be a single string or array (list).
I know how to parse if separately. but I'm looking for a way to have a dynamic decoder to parse both of them.
The value field in the JSON is the case I'm talking about
Sample for single-value:
{
"filter":{
"op":"IN",
"field":"name",
"value": "testDuplicate"
}
}
Sample for multi-value:
{
"filter":{
"op":"IN",
"field":"name",
"value":["testDuplicate","tt"]
}
}
Structs for single value:
type DocumentTypeSearchRequest struct {
Filter DocTypeFilter `json:"filter"`
}
type DocTypeFilter struct {
Op string `json:"op"`
Field string `json:"field"`
Value string `json:"value"`
}
Structs for multi-value:
type DocumentTypeSearchRequest struct {
Filter DocTypeFilter `json:"filter"`
}
type DocTypeFilter struct {
Op string `json:"op"`
Field string `json:"field"`
Value []string `json:"value"`
}
One solution is to try to decode with one of them if failed use another one, but I'm not sure if that is the proper way to handle this problem.