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

Linda Hamilton
Release: 2024-11-07 05:58:03
Original
785 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!