I have these 'structures'
type Results struct {
Gender string `json:"gender"`
Name struct {
First string `json:"first"`
Last string `json:"last"`
} `json:"name"`
Location struct {
Postcode int `json:"postcode"`
}
Registered struct {
Date string `json:"date"`
} `json:"registered"`
}
type Info struct {
Seed string `json:"seed"`
Results int64 `json:"results"`
Page int64 `json:"page"`
Version string `json:"version"`
}
type Response struct {
Results []Results `json:"results"`
Info Info `json:"info"`
}
I' making a request to an external API and converting data to a JSON view.
I know in advance the types of all fields, but the problem occurs with the 'postcode' field. I'm getting different types of values, which is why I get a JSON decoding error.
In this case, 'postcode' can be one of three variants:
- string ~ "13353"
- int ~ 13353
- string ~ "13353postcode"
Changing the postcode
type from string
to json.Number
solved the problem.
But this solution does not satisfy the third "option".
I know I can try to create a custom type and implement an interface on it. Seems to me the best solution using json.RawMessage
. It’s the first I've faced this problem, So I'm still looking for an implementation of a solution to this and reading the documentation.
What's the best way solution in this case?
Thanks in advance.
question from:
https://stackoverflow.com/questions/66056003/how-to-unmarshall-data-to-json-with-unknown-field-types 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…