0

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

tama
  • 315
  • 2
  • 4
  • 11
  • Take a look at related Q&A [https://stackoverflow.com/questions/24642148/golang-type-conversion-between-slices-of-structs](https://stackoverflow.com/questions/24642148/golang-type-conversion-between-slices-of-structs) – putu Dec 29 '17 at 09:33
  • 1
    Note that `type MyFarm entity.Farm` is _not_ a [type alias](https://github.com/golang/proposal/blob/master/design/18130-type-alias.md). – Jonathan Hall Dec 29 '17 at 09:55
  • Finally, all you need is a byte slice corresponding to the data in JSON format and you know the fields you need. See https://blog.golang.org/json-and-go on how `Message` structure has been used, hope it should be fairly simple to work around. Finally when you demux it, it will still fill into your `entity.Farm` structure. – Ravi R Dec 29 '17 at 10:14

0 Answers0