Skip to content

Instantly share code, notes, and snippets.

@yusufpapurcu
Created March 19, 2022 14:07
Show Gist options
  • Save yusufpapurcu/d331a505f2dcfd93cade1c80e15a499c to your computer and use it in GitHub Desktop.
Save yusufpapurcu/d331a505f2dcfd93cade1c80e15a499c to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"fmt"
)
func main() {
a := emailCover{Email: "12323", CreatedAt: "1213123", FullName: "321321", CreditCardInfo: "123213", Items: "21323"}
str, err := json.Marshal(a)
fmt.Printf("%s\nerr:%s", string(str), err)
var b emailCover
err = json.Unmarshal(str, &b)
fmt.Printf("%v\nerr:%s", b, err)
}
type exampleStruct struct {
Email, CreatedAt, FullName, CreditCardInfo, Items string
}
func getDefaultsexamplestruct() exampleStruct {
return exampleStruct{
Email: "N/A", CreatedAt: "N/A", FullName: "N/A", CreditCardInfo: "N/A", Items: "N/A",
}
}
type emailCover exampleStruct
func (c *emailCover) UnmarshalJSON(data []byte) error {
var a exampleStruct
if err := json.Unmarshal(data, &a); err != nil {
return err
}
c.Email = a.Email
c.FullName = a.FullName
return nil
}
func (c emailCover) MarshalJSON() ([]byte, error) {
a := getDefaultsexamplestruct()
a.Email = c.Email
a.FullName = c.FullName
return json.Marshal(a)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment