0

I've been using

json.NewDecoder() 
err = decoder.Decode(&m)

to decode JSON and map into a custom struct. When I made a request with another JSON, decoder doesn't return an error. I used required for binding but It didn't change anything.

My custom struct looks like this

type UpdateUserInformationModel struct {
    Token                      string `json:"Token" binding:"required"`
    Name                       string `json:"Name" binding:"required"`
    Lastname                   string `json:"Lastname" binding:"required"`
    PhoneNumber                string
    ProfilePhotoInBase64String string
    AdditionalInformation      string
}

I made a request with this JSON

{
    "Token":"CHlBciGyuTsJ1B5JYLjT",
    "Name":"Mert"
}

and decoder doesn't return an error. Can anyone help me?

When I searched the net for the answer doing it manually. Do we have another option for checking if field exist on JSON automatically.

Mert Serin
  • 289
  • 6
  • 20
  • The json package doesn't use a "binding" tag, where are you getting this? – JimB Mar 14 '17 at 13:46
  • So how can check if json doesn't have required keys? Manually? – Mert Serin Mar 14 '17 at 13:47
  • You'll either have to do the validation manually or use a 3rd party package to do it for you, for example this one: https://github.com/go-playground/validator. [Here](https://github.com/go-playground/validator/blob/v9/examples/simple/main.go) is a simple example on how to use it. – mkopriva Mar 14 '17 at 14:29

0 Answers0