Is it possible to make marshall fail inside getJSONStr function after receiving some string?
package main
import (
"fmt"
"encoding/json"
)
type obj struct {
Name string `json:"name"`
}
func getJSONStr(s string) (*string, error) {
t := new(obj)
t.Name = s
b, err := json.Marshal(t)
if err != nil {
return nil, err
}
str := string(b)
return &str, nil
}
func main() {
str, err := getJSONStr("VALIDATE")
fmt.Println("str",*str)
fmt.Println("err",err)
}
I've been trying to make it but with no success.
You can implement json.Marshaler
for either obj
or the the specific field inside obj
. This marshaler can check the value of the field and return an error. Here's an example with a custom marshaler added for the Name
field which fails if Name
is "Boom!"
type NameWithValidation string
func (s NameWithValidation) MarshalJSON() ([]byte, error) {
if string(s) == "Boom!" {
return nil, fmt.Errorf("Name '%s' failed validation", s)
}
return json.Marshal(string(s))
}
type obj struct {
Name NameWithValidation `json:"name"`
}
When marshalling, json.Marshal()
checks if the type implements json.Marshaler
and if that's true, it calls MarshalJSON()
on them instead of trying to marshal the item itself.
From the Godocs
Channel, complex, and function values cannot be encoded in JSON. Attempting to encode such a value causes Marshal to return an UnsupportedTypeError.
So if you were to modify your struct to include any of these types and attempt to marshal it you would then get an error.