My goal is to create JSON marshal from a struct but with different fields.
For example, my struct have UID, Name, and Type
fields, but I want to Marshal just 2 of them.
I have something like this:
package entity
type Farm struct {
UID string
Name string
Type string
}
-----------------------
package server
func(f entity.Farm) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
UID string `json:"uid"`
Name string `json:"name"`
}{
UID: f.UID,
Name: f.Name,
})
}
func main() {
farms := []entity.Farm{}
farms.append(farms, Farm{"123", "MyFarm1", "organic"})
farms.append(farms, Farm{"456", "MyFarm2", "organic"})
json, _ = json.Marshal(farms)
}
The problem is I cannot create custom method of MarshalJSON()
from entity.Farm
because its in the other package. Googling said that I should do custom type and make custom method of MarshalJSON()
from that. But I still don't know how to convert from my []entity.Farm
to []MyFarm
in my func main()
So here if I try to use custom type:
package server
type MyFarm entity.Farm
func(mf MyFarm) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
UID string `json:"uid"`
Name string `json:"name"`
}{
UID: mf.UID,
Name: mf.Name,
})
}
func main() {
farms := []entity.Farm{}
farms.append(farms, Farm{"123", "MyFarm1", "organic"})
farms.append(farms, Farm{"456", "MyFarm2", "organic"})
// Here I need to convert farms slice to []MyFarm slice
// so that I can use my custom MarshalJSON() from MyFarm
}
So how can I convert that farms
slice to slice of MyFarm
so that I can use my custom MarshalJSON() from MyFarm?
And I cannot change the Farm struct's package to package server