Last active
November 2, 2023 12:59
-
-
Save ik5/a4521a4166302efecc3d3f8ea8080912 to your computer and use it in GitHub Desktop.
Example of custom unmarshal of JSON in golang
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" | |
"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 | |
} | |
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"}
}
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
can u also add example of json?