Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to marshal struct when some members are protected/inner/hidden

Tags:

go

marshalling

How do ensure the fields in this LookupCode struct are included when marshalling?

package main

import (
    "encoding/json"
    "fmt"
)

type LookupCode struct {
    code string `json:"code"`
    name string `json:"name"`
}

func (l *LookupCode) GetCode() string {
    return l.code
}

func main() {
    c := &LookupCode{
        code: "A",
        name: "Apple",
    }

    b, _ := json.MarshalIndent(c, "", "\t")

    fmt.Println(string(b))
}

http://play.golang.org/p/my52DAn0-Z


1 Answers

You can by implementing the json.Marshaller interface:

Full Example: http://play.golang.org/p/8mIcPwX92P

// Implement json.Unmarshaller
func (l *LookupCode) UnmarshalJSON(b []byte) error {
    var tmp struct {
        Code string `json:"code"`
        Name string `json:"name"`
    }
    err := json.Unmarshal(b, &tmp)
    if err != nil {
        return err
    }
    l.code = tmp.Code
    l.name = tmp.Name
    return nil 
}

func (l *LookupCode) MarshalJSON() ([]byte, error) {
    return json.Marshal(struct {
        Code string `json:"code"`
        Name string `json:"name"`
    }{
        Code: l.code,
        Name: l.name,
    })
}
like image 98
fabrizioM Avatar answered Jan 21 '26 08:01

fabrizioM