When dealing with JSON responses, it may be necessary to preserve certain nested objects as raw strings or byte arrays instead of having them parsed into Go structures. To address this, we will explore a solution using the json.RawMessage type from the encoding/json package.
In your specific scenario, the following JSON:
{ "id" : 15, "foo" : { "foo": 123, "bar": "baz" } }
was to be unmarshalled into a Go structure with an ID field of type int64 and a Foo field of type []byte. The error you encountered, "json: cannot unmarshal object into Go value of type []uint8," indicates that the unmarshalling process was attempting to parse the foo object into a Go value, which is not intended behavior.
The json.RawMessage type provides a solution for this problem. As its documentation states, it is "a raw encoded JSON object" that can be used to delay JSON decoding or precompute a JSON encoding. Using json.RawMessage, you can effectively preserve the foo object as a raw byte array in your Go structure:
import ( "encoding/json" "fmt" ) type Bar struct { ID int64 `json:"id"` Foo json.RawMessage `json:"foo"` } func main() { var jsonStr = []byte(`{ "id" : 15, "foo" : { "foo": 123, "bar": "baz" } }`) var bar Bar err := json.Unmarshal(jsonStr, &bar) if err != nil { panic(err) } fmt.Printf("%+v\n", bar) }
Output:
{Id:15 Foo:[123 32 34 102 111 111 34 58 32 49 50 51 44 32 34 98 97 114 34 58 32 34 98 97 122 34 32 125]}
By leveraging json.RawMessage, you can now successfully Unmarshal the JSON into a Go structure that treats the foo object as a byte array.
The above is the detailed content of How to Unmarshal JSON Nested Objects as Byte Arrays in Go?. For more information, please follow other related articles on the PHP Chinese website!