package main
import (
"encoding/json"
"fmt"
"log"
"reflect"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
City string `json:"city"`
}
func mapDataToStruct(data map[string]interface{}, target interface{}) {
v := reflect.ValueOf(target).Elem()
for key, value := range data {
field := v.FieldByName(key)
if !field.IsValid() {
log.
Printf("Invalid field name: %s\n", key
) continue
}
if !field.CanSet() {
log.
Printf("Cannot set field: %s\n", key
) continue
}
// Handle type conversion
switch field.Kind() {
case reflect.String:
if strVal, ok := value.(string); ok {
field.SetString(strVal)
} else {
log.
Printf("Field %s expects a string\n", key
) }
case reflect.Int:
if floatVal, ok := value.(float64); ok {
field.SetInt(int64(floatVal)) // Convert float64 to int64
} else if intVal, ok := value.(int); ok {
field.SetInt(int64(intVal))
} else {
log.
Printf("Field %s expects an int\n", key
) }
default:
log.
Printf("Unsupported field type for %s\n", key
) }
}
}
func main() {
jsonData := `{"name": "John Doe", "age": 30, "city": "New York"}`
var person Person
// Parse JSON into a map
data := make(map[string]interface{})
if err := json.Unmarshal([]byte(jsonData), &data); err != nil {
log.
Fatalf("Error parsing JSON: %v", err
) }
// Map the data to the struct using reflection
mapDataToStruct(data, &person)
// Print the resulting struct
fmt.Println("Mapped Person:")
fmt.Printf("%+v\n", person)
}
cGFja2FnZSBtYWluCgppbXBvcnQgKAoJImVuY29kaW5nL2pzb24iCgkiZm10IgoJImxvZyIKCSJyZWZsZWN0IgopCgp0eXBlIFBlcnNvbiBzdHJ1Y3QgewoJTmFtZSBzdHJpbmcgYGpzb246Im5hbWUiYAoJQWdlICBpbnQgICAgYGpzb246ImFnZSJgCglDaXR5IHN0cmluZyBganNvbjoiY2l0eSJgCn0KCmZ1bmMgbWFwRGF0YVRvU3RydWN0KGRhdGEgbWFwW3N0cmluZ11pbnRlcmZhY2V7fSwgdGFyZ2V0IGludGVyZmFjZXt9KSB7Cgl2IDo9IHJlZmxlY3QuVmFsdWVPZih0YXJnZXQpLkVsZW0oKQoKCWZvciBrZXksIHZhbHVlIDo9IH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