The JSON Request Body:
{
"ifr": "b997c96cb360",
"ste": "EN",
"tye": "random",
"description": "desc",
"creationDate": "2023-04-06 06:01:24",
"modifiedDate": "2023-04-11 09:44:48"
}
Struct :
type M struct {
Ifr string `xml:"ifr,omitempty" json:"ifr,omitempty" validate:"required"`
Ste string `xml:"ste,omitempty" json:"ste,omitempty"`
Tye string `json:"tye,omitempty" xml:"tye,omitempty"`
Description string `xml:"description,omitempty" json:"description,omitempty"`
CreationDate time.Time `xml:"creationDate,omitempty" json:"creationDate,omitempty"`
ModifiedDate time.Time `xml:"modifiedDate,omitempty" json:"modifiedDate,omitempty"`
}
**When the above json body is passed for Un-Marshalling, I get this error:
error(time.ParseError) {Layout: ""2006-01-02T15:04:05Z07:00"", Value: ""2023-04-06 06:01:24"", LayoutElem: "T", ValueElem: " 06:01:24"", Message: ""}
Function :
func ConvertRequestBodyIntoCustomStruct(ctx *gin.Context, structure interface{}) *appError.AppError {
//Reading the request body
body, _ := ioutil.ReadAll(ctx.Request.Body)
//obtaining the content-type
contentType := ctx.Request.Header.Get("Content-Type")
//un-marshalling the request based on content-type
if contentType == constants.APPLICAITON_XML {
err := xml.Unmarshal(body, &structure)
if err != nil {
return appError.NewValidationError(appError.ErrInUnMarshalling, appError.ErrInUnMarshalling, appError.ErrInUnMarshalling)
}
} else {
err := json.Unmarshal(body, &structure)
if err != nil {
return appError.NewValidationError(appError.ErrInUnMashling, appError.ErrCodeInUnMashling, appError.ErrInUnMashling)
}
}
return nil
}
I expect it not to throw the above mentioned error while unmarshalling.
The error you are encountering is related to the format of the CreationDate and ModifiedDate fields in the JSON request body. According to the error message, the layout used for parsing the time string is ""2006-01-02T15:04:05Z07:00"", but the actual value in the request body is "2023-04-06 06:01:24".
To fix this issue, you need to update the layout used for parsing the time string to match the format of the time values in the JSON request body. Based on the example JSON request body you provided, the correct layout should be "2006-01-02 15:04:05".
Here's an updated version of your code with the correct layout:
By updating the time layout to match the format of the time values in the JSON request body, you should be able to successfully unmarshal the request without encountering the "time.ParseError" error.