Created
March 19, 2022 14:07
-
-
Save yusufpapurcu/d331a505f2dcfd93cade1c80e15a499c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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