In Go, unmarshalling JSON data into a predefined struct is straightforward. However, what if you want to customize the data structure even further? Suppose you have the following JSON data:
<code class="json">{ "Asks": [ [21, 1], [22, 1] ], "Bids": [ [20, 1], [19, 1] ] }</code>
You can easily define a struct to match this structure:
<code class="go">type Message struct { Asks [][]float64 `json:"Asks"` Bids [][]float64 `json:"Bids"` }</code>
However, you may prefer a more specialized data structure:
<code class="go">type Message struct { Asks []Order `json:"Asks"` Bids []Order `json:"Bids"` } type Order struct { Price float64 Volume float64 }</code>
To unmarshal the JSON data into this specialized structure, you can implement the json.Unmarshaler interface on your Order struct:
<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 specifies that the Order type should be decoded from a two-element array of floats rather than the default representation for a struct (an object).
Example Usage:
<code class="go">m := new(Message) err := json.Unmarshal(b, &m) fmt.Println(m.Asks[0].Price) // Output: 21</code>
By implementing json.Unmarshaler, you can easily customize the unmarshalling process to suit your specific data structure requirements.
The above is the detailed content of How to Customize JSON Unmarshaling into a Specific Struct in Go?. For more information, please follow other related articles on the PHP Chinese website!