fork download
  1. package main
  2.  
  3. import (
  4. "encoding/json"
  5. "fmt"
  6. "log"
  7. "reflect"
  8. )
  9.  
  10. type Person struct {
  11. Name string `json:"name"`
  12. Age int `json:"age"`
  13. City string `json:"city"`
  14. }
  15.  
  16. func mapDataToStruct(data map[string]interface{}, target interface{}) {
  17. v := reflect.ValueOf(target).Elem()
  18.  
  19. for key, value := range data {
  20. field := v.FieldByName(key)
  21. if !field.IsValid() {
  22. log.Printf("Invalid field name: %s\n", key)
  23. continue
  24. }
  25. if !field.CanSet() {
  26. log.Printf("Cannot set field: %s\n", key)
  27. continue
  28. }
  29.  
  30. // Handle type conversion
  31. switch field.Kind() {
  32. case reflect.String:
  33. if strVal, ok := value.(string); ok {
  34. field.SetString(strVal)
  35. } else {
  36. log.Printf("Field %s expects a string\n", key)
  37. }
  38. case reflect.Int:
  39. if floatVal, ok := value.(float64); ok {
  40. field.SetInt(int64(floatVal)) // Convert float64 to int64
  41. } else if intVal, ok := value.(int); ok {
  42. field.SetInt(int64(intVal))
  43. } else {
  44. log.Printf("Field %s expects an int\n", key)
  45. }
  46. default:
  47. log.Printf("Unsupported field type for %s\n", key)
  48. }
  49. }
  50. }
  51.  
  52. func main() {
  53. jsonData := `{"name": "John Doe", "age": 30, "city": "New York"}`
  54.  
  55. var person Person
  56.  
  57. // Parse JSON into a map
  58. data := make(map[string]interface{})
  59. if err := json.Unmarshal([]byte(jsonData), &data); err != nil {
  60. log.Fatalf("Error parsing JSON: %v", err)
  61. }
  62.  
  63. // Map the data to the struct using reflection
  64. mapDataToStruct(data, &person)
  65.  
  66. // Print the resulting struct
  67. fmt.Println("Mapped Person:")
  68. fmt.Printf("%+v\n", person)
  69. }
  70.  
  71.  
Success #stdin #stdout #stderr 0.01s 5284KB
stdin
Standard input is empty
stdout
Mapped Person:
{Name: Age:0 City:}
stderr
2024/12/17 06:19:52 Invalid field name: name
2024/12/17 06:19:52 Invalid field name: age
2024/12/17 06:19:52 Invalid field name: city