Home >Backend Development >Golang >How to Customize JSON Unmarshaling into a Specific Struct in Go?

How to Customize JSON Unmarshaling into a Specific Struct in Go?

Linda Hamilton
Linda HamiltonOriginal
2024-11-07 05:58:03912browse

How to Customize JSON Unmarshaling into a Specific Struct in Go?

Custom Unmarshaling of JSON Data into a Specific Struct

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>

Custom Unmarshaling Using json.Unmarshaler

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn