Skip to content

Instantly share code, notes, and snippets.

@ik5
Last active April 15, 2025 13:27
Show Gist options
  • Select an option

  • Save ik5/a4521a4166302efecc3d3f8ea8080912 to your computer and use it in GitHub Desktop.

Select an option

Save ik5/a4521a4166302efecc3d3f8ea8080912 to your computer and use it in GitHub Desktop.

Revisions

  1. ik5 revised this gist Sep 21, 2022. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion custom_json_unmarshal.go
    Original file line number Diff line number Diff line change
    @@ -27,7 +27,7 @@ func (c *To) UnmarshalJSON(data []byte) error {
    *c = append(*c, items.String())

    case reflect.Slice:
    *c = make(Contacts, 0, items.Len())
    *c = make(To, 0, items.Len())
    for i := 0; i < items.Len(); i++ {
    item := items.Index(i)
    switch item.Kind() {
  2. ik5 created this gist Jun 25, 2019.
    43 changes: 43 additions & 0 deletions custom_json_unmarshal.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    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(Contacts, 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
    }