Skip to content

Instantly share code, notes, and snippets.

@whitekid
Created October 4, 2018 13:38
Show Gist options
  • Save whitekid/3669df0a8016b34a8a52718ec309e8a9 to your computer and use it in GitHub Desktop.
Save whitekid/3669df0a8016b34a8a52718ec309e8a9 to your computer and use it in GitHub Desktop.
golang json failback
package main
import (
"encoding/json"
"strings"
)
type Data struct {
Build struct {
Name string `json:"name"`
} `json:"build"`
}
func (d *Data) UnmarshalJSON(data []byte) error {
type oldData struct {
Build string `json:"build"`
}
o := oldData{}
if err := json.Unmarshal(data, &o); err == nil {
return nil
}
type typeAlias *Data
return json.Unmarshal(data, typeAlias(d))
}
func main() {
for _, test := range []struct {
raw string
expected string
}{
{
raw: `{"build": "invalid data"}`,
expected: "",
},
{
raw: `{"build": {"name": "hello"}}`,
expected: "hello",
},
} {
d := &Data{}
if err := json.NewDecoder(strings.NewReader(test.raw)).Decode(d); err != nil {
panic(err)
}
if test.expected != d.Build.Name {
panic("Not equals")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment