To serialize and deserialize JSON using reflection in Golang, you can follow these steps:
Here's an example that demonstrates this process:
package main
import (
"encoding/json"
"fmt"
"reflect"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
Address string `json:"address"`
}
func main() {
// Serialization
person := Person{Name: "John Doe", Age: 30, Address: "123 Main St"}
jsonData, err := json.Marshal(person)
if err != nil {
fmt.Println("Serialization error:", err)
return
}
fmt.Println(string(jsonData))
// Deserialization
jsonStr := `{"name":"Jane Smith","age":25,"address":"456 Elm St"}`
var newPerson Person
err = json.Unmarshal([]byte(jsonStr), &newPerson)
if err != nil {
fmt.Println("Deserialization error:", err)
return
}
fmt.Println("Name:", newPerson.Name)
fmt.Println("Age:", newPerson.Age)
fmt.Println("Address:", newPerson.Address)
// Accessing fields using reflection
personValue := reflect.ValueOf(newPerson)
personType := personValue.Type()
for i := 0; i < personValue.NumField(); i++ {
field := personValue.Field(i)
fieldType := personType.Field(i)
fmt.Println(fieldType.Name + ":", field.Interface())
}
}
In this example, we define a Person
struct with three fields: Name
, Age
, and Address
. We use the json
struct tags to map the struct fields to the corresponding JSON keys.
The main
function demonstrates both serialization and deserialization. For serialization, we use json.Marshal()
to convert the person
variable to a JSON byte slice. For deserialization, we use json.Unmarshal()
to convert the JSON string to a Person
struct.
Additionally, the example shows how to access the fields of a struct using reflection. We use reflect.ValueOf()
to get a reflect.Value
of the struct, and reflect.Type
to get its type. We iterate over the fields using NumField()
and use Interface()
to access the values of the fields.