Home > Backend Development > Golang > How to Unmarshal JSON into a Specific Struct Using an Interface Variable in Go?

How to Unmarshal JSON into a Specific Struct Using an Interface Variable in Go?

Susan Sarandon
Release: 2024-11-27 16:58:11
Original
618 people have browsed it

How to Unmarshal JSON into a Specific Struct Using an Interface Variable in Go?

How to Unmarshal JSON into a Specific Struct Using Interface Variables

Problem:

When unmarshaling JSON into an interface variable, the encoding/json package interprets it as a map. How can we instruct it to use a specific struct instead?

Explanation:

The JSON package requires a concrete type to target when unmarshaling. Passing an interface{} variable doesn't provide sufficient information, and the package defaults to map[string]interface{} for objects and []interface{} for arrays.

Solution:

There is no built-in way to tell json.Unmarshal to unmarshal into a concrete struct type using an interface variable. However, there is a workaround:

  1. Wrap a pointer to the desired struct in the interface variable.
func getFoo() interface{} {
    return &Foo{"bar"}
}
Copy after login
  1. Pass the wrapped pointer to json.Unmarshal.
err := json.Unmarshal(jsonBytes, fooInterface)
Copy after login
  1. Access the unmarshaled data through the interface variable.
fmt.Printf("%T %+v", fooInterface, fooInterface)
Copy after login

Example:

The following code demonstrates the technique:

package main

import (
    "encoding/json"
    "fmt"
)

type Foo struct {
    Bar string `json:"bar"`
}  

func getFoo() interface{} {
    return &Foo{"bar"}
}

func main() {

    fooInterface := getFoo() 
    
    myJSON := `{"bar":"This is the new value of bar"}`
    jsonBytes := []byte(myJSON)

    err := json.Unmarshal(jsonBytes, fooInterface)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Printf("%T %+v", fooInterface, fooInterface) // prints: *main.Foo &{Bar:This is the new value of bar}
}
Copy after login

The above is the detailed content of How to Unmarshal JSON into a Specific Struct Using an Interface Variable in Go?. For more information, please follow other related articles on the PHP Chinese website!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template