Created
October 4, 2018 13:38
-
-
Save whitekid/3669df0a8016b34a8a52718ec309e8a9 to your computer and use it in GitHub Desktop.
golang json failback
This file contains hidden or 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" | |
"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