简体   繁体   中英

Golang - Returning null value when return type is string

I have a go struct something like this

type Country struct {
    WhoAllAreComing    []string `json:"attendees"`
    NameOfThePlace     string   `json:"name"`
    EventDate          string   `json:"eventDate"`
}

This is the response struct that I need to send back after ingesting the input and manipulating it.

Now if suppose the EventDate is empty, I need to pass a null in the json response and not an empty string. How do we convert an empty string in go to a null in json response.

Using json.Marshall to marshall my response into Json is just converting it to empty string for EventDate.

Use a pointer to return a null instead of an empty string.

type Country struct {
    WhoAllAreComing    []string `json:"attendees"`
    NameOfThePlace     string   `json:"name"`
    EventDate          *string   `json:"eventDate"`
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM