Home >Backend Development >Golang >How to Unmarshal JSON Data into a Custom Data Structure in Go?
Unmarshaling JSON Data into a Custom Data Structure
In Go, it's often necessary to unmarshal JSON data into specific data structures. This can be achieved by defining custom types and implementing the json.Unmarshaler interface.
Problem Statement
Suppose we have JSON data with two arrays of order information: Asks and Bids. We want to unmarshal this data into a struct with two fields: Asks and Bids, where each field is a slice of Order structs.
Custom Type and Unmarshaler Implementation
To create our desired data structure, we define a custom type called Order:
<code class="go">type Order struct { Price float64 Volume float64 }</code>
Next, we implement the json.Unmarshaler interface for the Order type. This allows us to specify how the JSON data should be parsed into our custom structure:
<code class="go">func (o *Order) UnmarshalJSON(data []byte) error { var v [2]float64 if err := json.Unmarshal(data, &v); err != nil { return err } o.Price = v[0] o.Volume = v[1] return nil }</code>
This implementation expects the JSON data for an Order to be an array of two floats, which represent the price and volume.
Unmarshaling the JSON Data
With our custom type and UnmarshalJSON implementation in place, we can now unmarshal the JSON data as follows:
<code class="go">b := []byte(`{"Asks": [[21, 1], [22, 1]] ,"Bids": [[20, 1], [19, 1]]}`) m := new(Message) if err := json.Unmarshal(b, &m); err != nil { // handle error } fmt.Println(m.Asks[0].Price) // 21</code>
By implementing the json.Unmarshaler interface, we have achieved our goal of unmarshaling the JSON data into a custom data structure that more accurately represents the order information.
The above is the detailed content of How to Unmarshal JSON Data into a Custom Data Structure in Go?. For more information, please follow other related articles on the PHP Chinese website!