I have two Database table. I want to get the values from those tables by mysql queries and pass it to the controller. There I bind it one struct and show the json values as response to the controller. But the problem is there are some uncommon columns between two table but I have to use every fields in common Struct. When I got the response for one table other table's field are showing empty in the json object and vice versa. How to show only the related fields in every json object?
Code:
Model:
type Student struct {
StudentId int
Name string
Address string
}
type Teacher struct {
TeacherId int
Name string
Address string
Department string
}
type TeacherStudent struct {
StudentId int
Name string
Address string
TeacherId int
Department string
}
Controller:
json.Unmarshal([]byte(datas), &ts)
c.Data["json"] = ts
c.ServeJSON()
Response in Postman:
[
{
"StudnetId": 501,
"Name": Mark,
"Address": Canbera,
"TeacherId": 0,
"Deparment": ""
},
{
"StudnetId": 0,
"Name": John,
"Address": Melbourne,
"TeacherId": 101,
"Deparment": "Science"
}]
For Studnet Response I Don't want to show the TeacherId and Department and For Teacher Record I don't want to show the StudentId in json Object.
CodePudding user response:
Answering my own question:
The solution for this is using json:"omitempty"
Referring to this article: https://www.sohamkamani.com/golang/omitempty/
Note: json:"omitempty"
works for the fields only. It will not work for the structs inside the structs. Also it will not work for the time.Time fields. Referring to this article to handle the time.Time issue: JSON omitempty With time.Time Field
Happy Coding!
CodePudding user response:
Also you can use json:"-"
for empty fields which is you want.