Skip to content

Instantly share code, notes, and snippets.

@ik5
Last active November 2, 2023 12:59
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ik5/a4521a4166302efecc3d3f8ea8080912 to your computer and use it in GitHub Desktop.
Save ik5/a4521a4166302efecc3d3f8ea8080912 to your computer and use it in GitHub Desktop.
Example of custom unmarshal of JSON in golang
package main
import (
"encoding/json"
"fmt"
"reflect"
)
type To []string
type Message struct {
From string `"json:from"`
To To `"json:to"`
Message string `"json:message"`
}
func (c *To) UnmarshalJSON(data []byte) error {
var nums interface{}
err := json.Unmarshal(data, &nums)
if err != nil {
return err
}
items := reflect.ValueOf(nums)
switch items.Kind() {
case reflect.String:
*c = append(*c, items.String())
case reflect.Slice:
*c = make(To, 0, items.Len())
for i := 0; i < items.Len(); i++ {
item := items.Index(i)
switch item.Kind() {
case reflect.String:
*c = append(*c, item.String())
case reflect.Interface:
*c = append(*c, item.Interface().(string))
}
}
}
return nil
}
@dozer111
Copy link

can u also add example of json?

@ik5
Copy link
Author

ik5 commented Sep 21, 2022

can u also add example of json?

Sure, it is very simple:

//...
func main() {
  jsonMsg := []byte(`{ "from": "me", "to": "you",  "message": "hello you" }`)
  var message Message

  err := json.Unmarshal(jsonMsg, &message)
  
  fmt.Printf("message: %#v | err: %v", message, err)

 // > message: main.Message{From:"me", To:main.To{"you"}, Message:"hello you"}
}

@dozer111
Copy link

can u also add example of json?

Sure, it is very simple:

//...
func main() {
  jsonMsg := []byte(`{ "from": "me", "to": "you",  "message": "hello you" }`)
  var message Message

  err := json.Unmarshal(jsonMsg, &message)
  
  fmt.Printf("message: %#v | err: %v", message, err)

 // > message: main.Message{From:"me", To:main.To{"you"}, Message:"hello you"}
}

thank you)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment