I have some JSON that can have either a number or a string as the first element. I always want to be able to store this as a string value but instead I get a crash as it is reading it as quite rightly so a number type.
I tried to force the unmarshalling as a string but this was not successful.
string `json:",string"`
I am following this guide which seems to fit my data nicely.
How can I always get this element at [0] to always read and save as a string?
Code & Playground below...
https://play.golang.org/p/KP4_1xPJiZ
package main
import "fmt"
import "log"
import "encoding/json"
const inputWorking = `
["AAAAAA", {"testcode" : "Sss"}, 66666666]
`
const inputBroken = `
[111111, {"testcode" : "Sss"}, 66666666]
`
type RawMessage struct {
AlwaysString string `json:",string"`
ClientData ClientData
ReceptionTime int
}
type ClientData struct {
testcode string
}
func main() {
var n RawMessage
if err := json.Unmarshal([]byte(inputWorking), &n); err != nil {
log.Fatal(err)
}
fmt.Printf("%#v
", n)
var o RawMessage
if err := json.Unmarshal([]byte(inputBroken), &o); err != nil {
log.Fatal(err)
}
fmt.Printf("%#v
", o)
}
func (n *RawMessage) UnmarshalJSON(buf []byte) error {
tmp := []interface{}{&n.AlwaysString, &n.ClientData, &n.ReceptionTime}
wantLen := len(tmp)
if err := json.Unmarshal(buf, &tmp); err != nil {
return err
}
if g, e := len(tmp), wantLen; g != e {
return fmt.Errorf("wrong number of fields in RawMessage: %d != %d", g, e)
}
return nil
}