Skip to content

Instantly share code, notes, and snippets.

@KhodeN
Created March 30, 2018 05:51
Show Gist options
  • Save KhodeN/76f15bde12d818a1c973c9732a7eaa32 to your computer and use it in GitHub Desktop.
Save KhodeN/76f15bde12d818a1c973c9732a7eaa32 to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"fmt"
)
// Int64Array в json может быть представлен и массивом и одним значением sic!
type Int64Array struct {
Values []int64
}
func (i Int64Array) MarshalJSON() ([]byte, error) {
if len(i.Values) == 1 {
return json.Marshal(i.Values[0])
}
return json.Marshal(i.Values)
}
func (i *Int64Array) UnmarshalJSON(b []byte) error {
if len(b) > 0 && b[0] == '[' {
values := []int64{}
err := json.Unmarshal(b, &values)
if err != nil {
return err
}
i.Values = values
} else {
var value int64 = 0
err := json.Unmarshal(b, &value)
if err != nil {
return err
}
i.Values = append(i.Values, value)
}
return nil
}
type Wrapper struct {
Code Int64Array "json:`code`"
}
func main() {
singleJSON := `{"code":34}`
res := &Wrapper{}
json.Unmarshal([]byte(singleJSON), res)
fmt.Printf("Single value: %v\n", res.Code.Values)
multiJSON := `{"code":[1,2,3]}`
res = &Wrapper{}
json.Unmarshal([]byte(multiJSON), res)
fmt.Printf("Multi value: %v\n", res.Code.Values)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment