Answer the question
In order to leave comments, you need to log in
How to convert an array with different things to JSON?
There is an array in which there will be all sorts of errors. Since the errors are different, the array type is "interface{}". When the errors are collected, they should be sent to the user in JSON. Here is the problem with this. json.Marshal doesn't return anything. How can an array with errors be encoded into JSON?
The way is this:
1. first the errors themselves
type ecError struct { // от него наследуются все ошибки
statusCode int
errorCode string
issuers []string
message string
}
type ecEUnknown struct {
ecError
}
type ecEValidationMinmax struct {
ecError
min int
max int
}
var ec = servus.Server.NewErrorCollector()
var issuers [] string
issuers = append(issuers, "ModelsBoot")
servus.Server.AddEValidationMinmax(&ec, issuers, "hello", 1,2)
servus.Server.AddEUnknown(&ec, issuers, "hello")
servus.Server.GetErrors(&ec)
func (e serverT) AddEUnknown(ec *errorCollectorT, issuers []string, message string) {
_error := ecEUnknown{
ecError{statusCode: 500, errorCode: "E_UNKNOWN", issuers: issuers, message: message},
}
ec.errorsArray = append(ec.errorsArray, _error)
}
var bytes, err = json.Marshal(ec.errorsArray)
if err != nil {
log.Println("json поломался")
}
log.Println(ec.errorsArray)
log.Println(string(bytes))
2021/08/12 15:25:50 [{{400 E_VALIDATION_MINMAX [ModelsBoot] hello} 1 2} {{500 E_UNKNOWN [ModelsBoot] hello}}]
2021/08/12 15:25:50 [{},{}]
Answer the question
In order to leave comments, you need to log in
You have fields in structures that are not exportable, i.e. everything starts with small letters.
JSON cannot export such fields.
Just rename it and it will work.
And it’s better to make the structures also with a big one, so that in the end it would be like this.
type EcError struct { // от него наследуются все ошибки
StatusCode int
ErrorCode string
Issuers []string
Message string
}
type EcEUnknown struct {
EcError
}
type EcEValidationMinmax struct {
EcError
Min int
Max int
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question