How to Unmarshal JSON Data into a Custom Data Structure in Go?

Susan Sarandon
Release: 2024-11-06 14:35:02
Original
718 people have browsed it

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

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

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

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!

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!