package main
import (
"encoding/json"
"fmt"
"log"
"reflect"
"strconv"
"strings" // Fixed: Added missing import
)
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, val := range data {
// Find the field case-insensitively
field := v.FieldByNameFunc(func(s string) bool { return strings.ToLower(s) == key })
if !field.IsValid() {
log.
Printf("Invalid key in data: %s\n", key
) continue
}
if field.CanSet() {
switch val.(type) {
case string:
if field.Kind() == reflect.Int {
intVal, err := strconv.Atoi(val.(string))
if err != nil {
log.
Printf("Error converting to int for field '%s': %v\n", key
, err
) continue
}
field.SetInt(int64(intVal))
} else {
field.SetString(val.(string))
}
case int:
if field.Kind() == reflect.Int {
field.SetInt(int64(val.(int)))
}
default:
log.
Printf("Unsupported type for field '%s': %T\n", key
, val
) }
} else {
log.
Printf("Field '%s' is not settable\n", key
) }
}
}
func main() {
inputData := map[string]interface{}{
"name": "John Doe",
"age": 30,
"city": "New York",
"gender": "male", // Unsupported field
}
var person Person
if err := json.Unmarshal([]byte(`{"name":"Alice"}`), &person); err != nil {
panic(err)
}
fmt.Println("Original Person:", person)
mapDataToStruct(inputData, &person)
fmt.Println("\nPerson after mapping:", person)
}
cGFja2FnZSBtYWluCgppbXBvcnQgKAoJImVuY29kaW5nL2pzb24iCgkiZm10IgoJImxvZyIKCSJyZWZsZWN0IgoJInN0cmNvbnYiCgkic3RyaW5ncyIgLy8gRml4ZWQ6IEFkZGVkIG1pc3NpbmcgaW1wb3J0CikKCnR5cGUgUGVyc29uIHN0cnVjdCB7CglOYW1lIHN0cmluZyBganNvbjoibmFtZSJgCglBZ2UgIGludCAgICBganNvbjoiYWdlImAKCUNpdHkgc3RyaW5nIGBqc29uOiJjaXR5ImAKfQoKZnVuYyBtYXBEYXRhVG9TdHJ1Y3QoZGF0YSBtYXBbc3RyaW5nXWludGVyZmFjZXt9LCB0YXJnZXQgaW50ZXJmYWNle30pIHsKCXYg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