fork download
  1. package main
  2.  
  3. import (
  4. "encoding/json"
  5. "fmt"
  6. "log"
  7. "reflect"
  8. "strconv"
  9. "strings" // Fixed: Added missing import
  10. )
  11.  
  12. type Person struct {
  13. Name string `json:"name"`
  14. Age int `json:"age"`
  15. City string `json:"city"`
  16. }
  17.  
  18. func mapDataToStruct(data map[string]interface{}, target interface{}) {
  19. v := reflect.ValueOf(target).Elem()
  20. for key, val := range data {
  21. // Find the field case-insensitively
  22. field := v.FieldByNameFunc(func(s string) bool { return strings.ToLower(s) == key })
  23. if !field.IsValid() {
  24. log.Printf("Invalid key in data: %s\n", key)
  25. continue
  26. }
  27. if field.CanSet() {
  28. switch val.(type) {
  29. case string:
  30. if field.Kind() == reflect.Int {
  31. intVal, err := strconv.Atoi(val.(string))
  32. if err != nil {
  33. log.Printf("Error converting to int for field '%s': %v\n", key, err)
  34. continue
  35. }
  36. field.SetInt(int64(intVal))
  37. } else {
  38. field.SetString(val.(string))
  39. }
  40. case int:
  41. if field.Kind() == reflect.Int {
  42. field.SetInt(int64(val.(int)))
  43. }
  44. default:
  45. log.Printf("Unsupported type for field '%s': %T\n", key, val)
  46. }
  47. } else {
  48. log.Printf("Field '%s' is not settable\n", key)
  49. }
  50. }
  51. }
  52.  
  53. func main() {
  54. inputData := map[string]interface{}{
  55. "name": "John Doe",
  56. "age": 30,
  57. "city": "New York",
  58. "gender": "male", // Unsupported field
  59. }
  60.  
  61. var person Person
  62. if err := json.Unmarshal([]byte(`{"name":"Alice"}`), &person); err != nil {
  63. panic(err)
  64. }
  65. fmt.Println("Original Person:", person)
  66.  
  67. mapDataToStruct(inputData, &person)
  68.  
  69. fmt.Println("\nPerson after mapping:", person)
  70. }
  71.  
Success #stdin #stdout #stderr 0s 5272KB
stdin
Standard input is empty
stdout
Original Person: {Alice 0 }

Person after mapping: {John Doe 30 New York}
stderr
2024/12/17 06:21:19 Invalid key in data: gender