You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
2.0 KiB

  1. package JsonSerialization
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "strings"
  7. "git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Models"
  8. schema "github.com/Kangaroux/go-map-schema"
  9. )
  10. func DeserializeUser(data []byte, allowMissing []string, allowAllMissing bool) (Models.User, error) {
  11. var (
  12. userData Models.User = Models.User{}
  13. jsonStructureTest map[string]interface{} = make(map[string]interface{})
  14. jsonStructureTestResults *schema.CompareResults
  15. field schema.FieldMissing
  16. allowed string
  17. missingFields []string
  18. i int
  19. err error
  20. )
  21. // Verify the JSON has the correct structure
  22. json.Unmarshal(data, &jsonStructureTest)
  23. jsonStructureTestResults, err = schema.CompareMapToStruct(
  24. &userData,
  25. jsonStructureTest,
  26. &schema.CompareOpts{
  27. ConvertibleFunc: CanConvert,
  28. TypeNameFunc: schema.DetailedTypeName,
  29. })
  30. if err != nil {
  31. return userData, err
  32. }
  33. if len(jsonStructureTestResults.MismatchedFields) > 0 {
  34. return userData, errors.New(fmt.Sprintf(
  35. "MismatchedFields found when deserializing data: %s",
  36. jsonStructureTestResults.Errors().Error(),
  37. ))
  38. }
  39. // Remove allowed missing fields from MissingFields
  40. for _, allowed = range allowMissing {
  41. for i, field = range jsonStructureTestResults.MissingFields {
  42. if allowed == field.String() {
  43. jsonStructureTestResults.MissingFields = append(
  44. jsonStructureTestResults.MissingFields[:i],
  45. jsonStructureTestResults.MissingFields[i+1:]...,
  46. )
  47. }
  48. }
  49. }
  50. if !allowAllMissing && len(jsonStructureTestResults.MissingFields) > 0 {
  51. for _, field = range jsonStructureTestResults.MissingFields {
  52. missingFields = append(missingFields, field.String())
  53. }
  54. return userData, errors.New(fmt.Sprintf(
  55. "MissingFields found when deserializing data: %s",
  56. strings.Join(missingFields, ", "),
  57. ))
  58. }
  59. // Deserialize the JSON into the struct
  60. err = json.Unmarshal(data, &userData)
  61. if err != nil {
  62. return userData, err
  63. }
  64. return userData, err
  65. }