github.com/isyscore/isc-gobase@v1.5.3-0.20231218061332-cbc7451899e9/isc/convert.go (about) 1 package isc 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "io" 7 "reflect" 8 "strconv" 9 "strings" 10 "unicode" 11 12 "gopkg.in/yaml.v2" 13 ) 14 15 type ChangeError struct { 16 ErrMsg string 17 } 18 19 func (error *ChangeError) Error() string { 20 return error.ErrMsg 21 } 22 23 func ListToMap[K comparable, V any](list []Pair[K, V]) map[K]V { 24 m := make(map[K]V) 25 for _, item := range list { 26 m[item.First] = item.Second 27 } 28 return m 29 } 30 31 func MapToList[K comparable, V any](m map[K]V) []Pair[K, V] { 32 var n []Pair[K, V] 33 for k, v := range m { 34 n = append(n, NewPair(k, v)) 35 } 36 return n 37 } 38 39 func ToMap(data any) map[string]any { 40 if nil == data { 41 return nil 42 } 43 if reflect.TypeOf(data).Kind() == reflect.Map { 44 resultMap := map[string]any{} 45 dataValue := reflect.ValueOf(data) 46 for mapR := dataValue.MapRange(); mapR.Next(); { 47 mapKey := mapR.Key() 48 mapValue := mapR.Value() 49 resultMap[ToString(mapKey.Interface())] = mapValue.Interface() 50 } 51 return resultMap 52 } else if reflect.TypeOf(data).Kind() == reflect.Struct { 53 resultMap := map[string]any{} 54 jsonStr, err := json.Marshal(data) 55 if err != nil { 56 return resultMap 57 } 58 err = yaml.Unmarshal(jsonStr, &resultMap) 59 if err != nil { 60 return resultMap 61 } 62 return resultMap 63 } 64 return nil 65 } 66 67 func IsNumber(fieldKing reflect.Kind) bool { 68 switch fieldKing { 69 case reflect.Int: 70 return true 71 case reflect.Int8: 72 return true 73 case reflect.Int16: 74 return true 75 case reflect.Int32: 76 return true 77 case reflect.Int64: 78 return true 79 case reflect.Uint: 80 return true 81 case reflect.Uint8: 82 return true 83 case reflect.Uint16: 84 return true 85 case reflect.Uint32: 86 return true 87 case reflect.Uint64: 88 return true 89 case reflect.Float32: 90 return true 91 case reflect.Float64: 92 return true 93 default: 94 return false 95 } 96 } 97 98 // IsBaseType 是否是常见基本类型 99 func IsBaseType(fieldType reflect.Type) bool { 100 fieldKind := fieldType.Kind() 101 if fieldKind == reflect.Ptr { 102 fieldKind = fieldType.Elem().Kind() 103 } 104 105 switch fieldKind { 106 case reflect.Int: 107 return true 108 case reflect.Int8: 109 return true 110 case reflect.Int16: 111 return true 112 case reflect.Int32: 113 return true 114 case reflect.Int64: 115 return true 116 case reflect.Uint: 117 return true 118 case reflect.Uint8: 119 return true 120 case reflect.Uint16: 121 return true 122 case reflect.Uint32: 123 return true 124 case reflect.Uint64: 125 return true 126 case reflect.Float32: 127 return true 128 case reflect.Float64: 129 return true 130 case reflect.Bool: 131 return true 132 case reflect.String: 133 return true 134 default: 135 if fieldType.String() == "time.Time" { 136 return true 137 } 138 return false 139 } 140 } 141 142 func ToJsonString(value any) string { 143 if value == nil { 144 return "" 145 } 146 bytes, err := json.Marshal(value) 147 if err != nil { 148 return "" 149 } 150 return string(bytes) 151 } 152 153 func ToString(value any) string { 154 if value == nil { 155 return "" 156 } 157 if reflect.TypeOf(value).Kind() == reflect.String { 158 return value.(string) 159 } 160 161 return fmt.Sprintf("%v", value) 162 } 163 164 func ToInt(value any) int { 165 if value == nil { 166 return 0 167 } 168 result, err := ToValue(value, reflect.Int) 169 if err != nil { 170 return 0 171 } 172 return result.(int) 173 } 174 175 func ToInt8(value any) int8 { 176 if value == nil { 177 return 0 178 } 179 result, err := ToValue(value, reflect.Int8) 180 if err != nil { 181 return 0 182 } 183 return result.(int8) 184 } 185 186 func ToInt16(value any) int16 { 187 if value == nil { 188 return 0 189 } 190 result, err := ToValue(value, reflect.Int16) 191 if err != nil { 192 return 0 193 } 194 return result.(int16) 195 } 196 197 func ToInt32(value any) int32 { 198 if value == nil { 199 return 0 200 } 201 result, err := ToValue(value, reflect.Int32) 202 if err != nil { 203 return 0 204 } 205 return result.(int32) 206 } 207 208 func ToInt64(value any) int64 { 209 if value == nil { 210 return 0 211 } 212 result, err := ToValue(value, reflect.Int64) 213 if err != nil { 214 return 0 215 } 216 return result.(int64) 217 } 218 219 func ToUInt(value any) uint { 220 if value == nil { 221 return 0 222 } 223 result, err := ToValue(value, reflect.Uint) 224 if err != nil { 225 return 0 226 } 227 return result.(uint) 228 } 229 230 func ToUInt8(value any) uint8 { 231 if value == nil { 232 return 0 233 } 234 result, err := ToValue(value, reflect.Uint8) 235 if err != nil { 236 return 0 237 } 238 return result.(uint8) 239 } 240 241 func ToUInt16(value any) uint16 { 242 if value == nil { 243 return 0 244 } 245 result, err := ToValue(value, reflect.Uint16) 246 if err != nil { 247 return 0 248 } 249 return result.(uint16) 250 } 251 252 func ToUInt32(value any) uint32 { 253 if value == nil { 254 return 0 255 } 256 result, err := ToValue(value, reflect.Uint32) 257 if err != nil { 258 return 0 259 } 260 return result.(uint32) 261 } 262 263 func ToUInt64(value any) uint64 { 264 if value == nil { 265 return 0 266 } 267 result, err := ToValue(value, reflect.Uint64) 268 if err != nil { 269 return 0 270 } 271 return result.(uint64) 272 } 273 274 func ToFloat32(value any) float32 { 275 if value == nil { 276 return 0 277 } 278 result, err := ToValue(value, reflect.Float32) 279 if err != nil { 280 return 0 281 } 282 return result.(float32) 283 } 284 285 func ToFloat64(value any) float64 { 286 if value == nil { 287 return 0 288 } 289 result, err := ToValue(value, reflect.Float64) 290 if err != nil { 291 return 0 292 } 293 return result.(float64) 294 } 295 296 func ToBool(value any) bool { 297 if value == nil { 298 return false 299 } 300 result, err := ToValue(value, reflect.Bool) 301 if err != nil { 302 return false 303 } 304 return result.(bool) 305 } 306 307 func ToComplex64(value any) complex64 { 308 if value == nil { 309 return 0 310 } 311 result, err := ToValue(value, reflect.Complex64) 312 if err != nil { 313 return 0 314 } 315 return result.(complex64) 316 } 317 318 func ToComplex128(value any) complex128 { 319 if value == nil { 320 return 0 321 } 322 result, err := ToValue(value, reflect.Complex128) 323 if err != nil { 324 return 0 325 } 326 return result.(complex128) 327 } 328 329 func ToValue(value any, valueKind reflect.Kind) (any, error) { 330 if value == nil { 331 return nil, nil 332 } 333 valueStr := ToString(value) 334 return Cast(valueKind, valueStr) 335 } 336 337 func Cast(fieldKind reflect.Kind, valueStr string) (any, error) { 338 if valueStr == "nil" || valueStr == "" { 339 return nil, nil 340 } 341 switch fieldKind { 342 case reflect.Int: 343 return strconv.Atoi(valueStr) 344 case reflect.Int8: 345 v, err := strconv.ParseInt(valueStr, 10, 8) 346 if err != nil { 347 return nil, err 348 } 349 return int8(v), nil 350 case reflect.Int16: 351 v, err := strconv.ParseInt(valueStr, 10, 16) 352 if err != nil { 353 return nil, err 354 } 355 return int16(v), nil 356 case reflect.Int32: 357 v, err := strconv.ParseInt(valueStr, 10, 32) 358 if err != nil { 359 return nil, err 360 } 361 return int32(v), nil 362 case reflect.Int64: 363 return strconv.ParseInt(valueStr, 10, 64) 364 case reflect.Uint: 365 v, err := strconv.ParseUint(valueStr, 10, 0) 366 if err != nil { 367 return nil, err 368 } 369 return uint(v), nil 370 case reflect.Uint8: 371 v, err := strconv.ParseUint(valueStr, 10, 8) 372 if err != nil { 373 return nil, err 374 } 375 return uint8(v), nil 376 case reflect.Uint16: 377 v, err := strconv.ParseUint(valueStr, 10, 16) 378 if err != nil { 379 return nil, err 380 } 381 return uint16(v), nil 382 case reflect.Uint32: 383 v, err := strconv.ParseUint(valueStr, 10, 32) 384 if err != nil { 385 return nil, err 386 } 387 return uint32(v), nil 388 case reflect.Uint64: 389 return strconv.ParseUint(valueStr, 10, 64) 390 case reflect.Float32: 391 v, err := strconv.ParseFloat(valueStr, 32) 392 if err != nil { 393 return nil, err 394 } 395 return float32(v), nil 396 case reflect.Float64: 397 return strconv.ParseFloat(valueStr, 64) 398 case reflect.Complex64: 399 v, err := strconv.ParseComplex(valueStr, 64) 400 if err != nil { 401 return nil, err 402 } 403 return complex64(v), nil 404 case reflect.Complex128: 405 return strconv.ParseComplex(valueStr, 128) 406 case reflect.Bool: 407 return strconv.ParseBool(valueStr) 408 } 409 return valueStr, nil 410 } 411 412 // DataToObject 其他的类型能够按照小写字母转换到对象 413 // 其他类型: 414 // - 基本类型 415 // - 结构体类型:转换后对象 416 // - map类型 417 // - 集合/分片类型 418 // - 字符串类型:如果是json,则按照json进行转换 419 func DataToObject(data any, targetPtrObj any) error { 420 if data == nil { 421 return nil 422 } 423 targetType := reflect.TypeOf(targetPtrObj) 424 if targetType.Kind() != reflect.Ptr { 425 return &ChangeError{ErrMsg: "targetPtrObj type is not ptr"} 426 } 427 428 srcType := reflect.TypeOf(data) 429 if srcType.Kind() == reflect.Map { 430 return MapToObject(data, targetPtrObj) 431 } else if srcType.Kind() == reflect.Array || srcType.Kind() == reflect.Slice { 432 return ArrayToObject(data.([]any), targetPtrObj) 433 } else { 434 switch data.(type) { 435 case io.Reader: 436 return ReaderToObject(data.(io.Reader), targetPtrObj) 437 case string: 438 return StrToObject(data.(string), targetPtrObj) 439 case any: 440 return MapToObject(ToMap(data), targetPtrObj) 441 } 442 } 443 444 targetPtrValue := reflect.ValueOf(targetPtrObj) 445 rel, err := Cast(targetPtrValue.Elem().Kind(), fmt.Sprintf("%v", data)) 446 if err != nil { 447 return err 448 } 449 targetPtrValue.Elem().Set(reflect.ValueOf(rel)) 450 return nil 451 } 452 453 func ReaderToObject(reader io.Reader, targetPtrObj any) error { 454 if reader == nil { 455 return nil 456 } 457 targetType := reflect.TypeOf(targetPtrObj) 458 if targetType.Kind() != reflect.Ptr { 459 return &ChangeError{ErrMsg: "targetPtrObj type is not ptr"} 460 } 461 data, err := io.ReadAll(reader) 462 if err != nil { 463 return err 464 } 465 return StrToObject(string(data), targetPtrObj) 466 } 467 468 func StrToObject(contentOfJson string, targetPtrObj any) error { 469 if contentOfJson == "" { 470 return &ChangeError{ErrMsg: "content is nil"} 471 } 472 473 targetType := reflect.TypeOf(targetPtrObj) 474 if targetType.Kind() != reflect.Ptr { 475 return &ChangeError{ErrMsg: "targetPtrObj type is not ptr"} 476 } 477 478 if !strings.HasPrefix(contentOfJson, "{") && !strings.HasPrefix(contentOfJson, "[") { 479 targetPtrValue := reflect.ValueOf(targetPtrObj) 480 rel, err := Cast(targetPtrValue.Elem().Kind(), contentOfJson) 481 if err != nil { 482 return err 483 } 484 targetPtrValue.Elem().Set(reflect.ValueOf(rel)) 485 } 486 487 if strings.HasPrefix(contentOfJson, "{") && (reflect.ValueOf(targetPtrObj).Elem().Kind() == reflect.Map || reflect.ValueOf(targetPtrObj).Elem().Kind() == reflect.Struct) { 488 resultMap := make(map[string]any) 489 err := json.Unmarshal([]byte(contentOfJson), &resultMap) 490 if err != nil { 491 return err 492 } 493 return MapToObject(resultMap, targetPtrObj) 494 } else if strings.HasPrefix(contentOfJson, "[") && (reflect.ValueOf(targetPtrObj).Elem().Kind() == reflect.Slice || reflect.ValueOf(targetPtrObj).Elem().Kind() == reflect.Array) { 495 var srcArray []any 496 err := json.Unmarshal([]byte(contentOfJson), &srcArray) 497 if err != nil { 498 return err 499 } 500 return ArrayToObject(srcArray, targetPtrObj) 501 } else { 502 targetPtrValue := reflect.ValueOf(targetPtrObj) 503 rel, err := Cast(targetPtrValue.Elem().Kind(), contentOfJson) 504 if err != nil { 505 return err 506 } 507 targetPtrValue.Elem().Set(reflect.ValueOf(rel)) 508 return nil 509 } 510 } 511 512 func ArrayToObject(dataArray any, targetPtrObj any) error { 513 if dataArray == nil { 514 return nil 515 } 516 517 if reflect.ValueOf(dataArray).Kind() != reflect.Array && reflect.ValueOf(dataArray).Kind() != reflect.Slice { 518 return &ChangeError{ErrMsg: "dataArray is array type"} 519 } 520 521 targetType := reflect.TypeOf(targetPtrObj) 522 if targetType.Kind() != reflect.Ptr { 523 return &ChangeError{ErrMsg: "targetPtrObj type is not ptr"} 524 } 525 526 if targetType.Elem().Kind() != reflect.Slice && targetType.Elem().Kind() != reflect.Array { 527 return &ChangeError{ErrMsg: "item of targetPtrObj type is not slice"} 528 } 529 530 srcValue := reflect.ValueOf(dataArray) 531 dstPtrValue := reflect.ValueOf(targetPtrObj) 532 533 dstPrtType := reflect.TypeOf(targetPtrObj) 534 dstType := dstPrtType.Elem() 535 dstItemType := dstType.Elem() 536 537 dstValue := reflect.MakeSlice(dstType, 0, 0) 538 539 for arrayIndex := 0; arrayIndex < srcValue.Len(); arrayIndex++ { 540 dataV := valueToTarget(srcValue.Index(arrayIndex), dstItemType) 541 if dataV.IsValid() { 542 if dataV.Kind() == reflect.Ptr { 543 dstValue = reflect.Append(dstValue, dataV.Elem()) 544 } else { 545 dstValue = reflect.Append(dstValue, dataV) 546 } 547 } 548 } 549 dstPtrValue.Elem().Set(dstValue) 550 return nil 551 } 552 553 func MapToObject(dataMap any, targetPtrObj any) error { 554 if dataMap == nil { 555 return nil 556 } 557 targetType := reflect.TypeOf(targetPtrObj) 558 if targetType.Kind() != reflect.Ptr { 559 return &ChangeError{ErrMsg: "targetPtrObj type is not ptr"} 560 } 561 562 if targetType.Elem().Kind() != reflect.Map && targetType.Elem().Kind() != reflect.Struct { 563 return &ChangeError{ErrMsg: "item of targetPtrObj type is not slice"} 564 } 565 566 if targetType.Elem().Kind() == reflect.Map { 567 srcValue := reflect.ValueOf(dataMap) 568 dstValue := reflect.ValueOf(targetPtrObj) 569 570 dstPtrType := reflect.TypeOf(targetPtrObj) 571 dstType := dstPtrType.Elem() 572 573 mapFieldValue := reflect.MakeMap(dstType) 574 for mapR := srcValue.MapRange(); mapR.Next(); { 575 mapKey := mapR.Key() 576 mapValue := mapR.Value() 577 578 mapKeyRealValue, err := Cast(mapFieldValue.Type().Key().Kind(), fmt.Sprintf("%v", mapKey.Interface())) 579 mapValueRealValue := valueToTarget(mapValue, mapFieldValue.Type().Elem()) 580 if err == nil { 581 if mapValueRealValue.Kind() == reflect.Ptr { 582 mapFieldValue.SetMapIndex(reflect.ValueOf(mapKeyRealValue), mapValueRealValue.Elem()) 583 } else { 584 mapFieldValue.SetMapIndex(reflect.ValueOf(mapKeyRealValue), mapValueRealValue) 585 } 586 } 587 } 588 dstValue.Elem().Set(mapFieldValue) 589 } else { 590 targetValue := reflect.ValueOf(targetPtrObj) 591 for index, num := 0, targetType.Elem().NumField(); index < num; index++ { 592 field := targetType.Elem().Field(index) 593 fieldValue := targetValue.Elem().Field(index) 594 595 doInvokeValue(reflect.ValueOf(dataMap), field, fieldValue) 596 } 597 } 598 return nil 599 } 600 601 func doInvokeValue(fieldMapValue reflect.Value, field reflect.StructField, fieldValue reflect.Value) { 602 // 私有字段不处理 603 if IsPrivate(field.Name) { 604 return 605 } 606 607 if fieldMapValue.Kind() == reflect.Ptr { 608 fieldMapValue = fieldMapValue.Elem() 609 } 610 611 var fValue reflect.Value 612 if v, exist := getValueFromMapValue(fieldMapValue, field.Name); exist { 613 // 兼容DataBaseUser格式读取 614 fValue = v 615 } else if v, exist := getValueFromMapValue(fieldMapValue, BigCamelToMiddleLine(field.Name)); exist { 616 // 兼容data-base-user格式读取 617 fValue = v 618 } else if v, exist := getValueFromMapValue(fieldMapValue, BigCamelToSmallCamel(field.Name)); exist { 619 // 兼容dataBaseUser格式读取 620 fValue = v 621 } else if v, exist := getValueFromMapValue(fieldMapValue, BigCamelToUnderLine(field.Name)); exist { 622 // 兼容data_base_user格式读取 623 fValue = v 624 } else if v, exist := getValueFromMapValue(fieldMapValue, field.Tag.Get("yaml")); exist { 625 // 兼容标签:yaml 626 fValue = v 627 } else if v, exist := getValueFromMapValue(fieldMapValue, field.Tag.Get("json")); exist { 628 // 兼容标签:json 629 fValue = v 630 } else { 631 return 632 } 633 634 if fieldValue.Kind() == reflect.Ptr { 635 fValue = fValue.Elem() 636 } 637 targetValue := valueToTarget(fValue, field.Type) 638 if targetValue.IsValid() { 639 if fieldValue.Kind() == reflect.Ptr { 640 if targetValue.Kind() == reflect.Ptr { 641 fieldValue.Elem().FieldByName(field.Name).Set(targetValue.Elem().Convert(field.Type)) 642 } else { 643 fieldValue.Elem().FieldByName(field.Name).Set(targetValue.Convert(field.Type)) 644 } 645 } else { 646 if targetValue.Kind() == reflect.Ptr { 647 fieldValue.Set(targetValue.Elem().Convert(field.Type)) 648 } else { 649 fieldValue.Set(targetValue.Convert(field.Type)) 650 } 651 } 652 } 653 } 654 655 func valueToTarget(srcValue reflect.Value, dstType reflect.Type) reflect.Value { 656 if dstType.Kind() == reflect.Struct { 657 if srcValue.Kind() == reflect.Ptr { 658 srcValue = srcValue.Elem() 659 } 660 sourceValue := reflect.ValueOf(srcValue.Interface()) 661 if sourceValue.Kind() == reflect.Map || sourceValue.Kind() == reflect.Struct { 662 mapFieldValue := reflect.New(dstType) 663 for index, num := 0, mapFieldValue.Type().Elem().NumField(); index < num; index++ { 664 field := mapFieldValue.Type().Elem().Field(index) 665 fieldValue := mapFieldValue.Elem().Field(index) 666 667 doInvokeValue(sourceValue, field, fieldValue) 668 } 669 return mapFieldValue 670 } 671 } else if dstType.Kind() == reflect.Map { 672 if srcValue.Kind() == reflect.Ptr { 673 srcValue = srcValue.Elem() 674 } 675 sourceValue := reflect.ValueOf(srcValue.Interface()) 676 if sourceValue.Kind() == reflect.Map { 677 mapFieldValue := reflect.MakeMap(dstType) 678 for mapR := sourceValue.MapRange(); mapR.Next(); { 679 mapKey := mapR.Key() 680 mapValue := mapR.Value() 681 682 mapKeyRealValue, err := Cast(mapFieldValue.Type().Key().Kind(), fmt.Sprintf("%v", mapKey.Interface())) 683 mapValueRealValue := valueToTarget(mapValue, mapFieldValue.Type().Elem()) 684 if err == nil { 685 if mapValueRealValue.Kind() == reflect.Ptr { 686 mapFieldValue.SetMapIndex(reflect.ValueOf(mapKeyRealValue), mapValueRealValue.Elem()) 687 } else { 688 mapFieldValue.SetMapIndex(reflect.ValueOf(mapKeyRealValue), mapValueRealValue) 689 } 690 } 691 } 692 return mapFieldValue 693 } else if sourceValue.Kind() == reflect.Struct { 694 srcType := reflect.TypeOf(sourceValue) 695 srcValue := reflect.ValueOf(sourceValue) 696 mapFieldValue := reflect.MakeMap(dstType) 697 698 for index, num := 0, srcType.NumField(); index < num; index++ { 699 field := srcType.Field(index) 700 fieldValue := srcValue.Field(index) 701 702 mapValueRealValue := ObjectToData(fieldValue.Interface()) 703 mapFieldValue.SetMapIndex(reflect.ValueOf(ToLowerFirstPrefix(field.Name)), reflect.ValueOf(mapValueRealValue)) 704 705 doInvokeValue(sourceValue, field, fieldValue) 706 } 707 return mapFieldValue 708 } 709 } else if dstType.Kind() == reflect.Slice || dstType.Kind() == reflect.Array { 710 if srcValue.Kind() == reflect.Ptr { 711 srcValue = srcValue.Elem() 712 } 713 sourceValue := reflect.ValueOf(srcValue.Interface()) 714 if sourceValue.Kind() == reflect.Slice || sourceValue.Kind() == reflect.Array { 715 arrayFieldValue := reflect.MakeSlice(dstType, 0, 0) 716 for arrayIndex := 0; arrayIndex < sourceValue.Len(); arrayIndex++ { 717 dataV := valueToTarget(sourceValue.Index(arrayIndex), dstType.Elem()) 718 if dataV.IsValid() { 719 if dataV.Kind() == reflect.Ptr { 720 arrayFieldValue = reflect.Append(arrayFieldValue, dataV.Elem()) 721 } else { 722 arrayFieldValue = reflect.Append(arrayFieldValue, dataV) 723 } 724 } 725 } 726 return arrayFieldValue 727 } 728 } else if IsBaseType(dstType) { 729 sourceValue := reflect.ValueOf(srcValue.Interface()) 730 if sourceValue.IsValid() && IsBaseType(sourceValue.Type()) { 731 v, err := Cast(dstType.Kind(), fmt.Sprintf("%v", srcValue.Interface())) 732 if err == nil { 733 return reflect.ValueOf(v) 734 } 735 } 736 } else if dstType.Kind() == reflect.Interface { 737 return reflect.ValueOf(ObjectToData(srcValue.Interface())) 738 } else if dstType.Kind() == reflect.Ptr { 739 return srcValue 740 } else { 741 v, err := Cast(dstType.Kind(), fmt.Sprintf("%v", srcValue.Interface())) 742 if err == nil { 743 return reflect.ValueOf(v) 744 } 745 } 746 return reflect.ValueOf(nil) 747 } 748 749 // ObjectToData 字段转化,其中对应字段为小写,map的话为小写 750 func ObjectToData(object any) any { 751 if object == nil || reflect.ValueOf(object).Kind() == reflect.Ptr { 752 return "{}" 753 } 754 755 // 只接收 map、struct、array、slice进行解析 756 objKind := reflect.ValueOf(object).Kind() 757 if objKind != reflect.Map && objKind != reflect.Struct && objKind != reflect.Array && objKind != reflect.Slice { 758 return object 759 } 760 761 if objKind == reflect.Map { 762 // Map 结构 763 resultMap := make(map[string]any) 764 objValue := reflect.ValueOf(object) 765 if objValue.Len() == 0 { 766 return "{}" 767 } 768 769 for mapR := objValue.MapRange(); mapR.Next(); { 770 mapKey := mapR.Key() 771 mapValue := mapR.Value() 772 773 v := doObjectChange(reflect.TypeOf(mapValue.Interface()), mapValue.Interface()) 774 if v != nil { 775 resultMap[ToLowerFirstPrefix(ToString(mapKey.Interface()))] = v 776 } 777 } 778 return resultMap 779 } else if objKind == reflect.Struct { 780 // Struct 结构 781 resultMap := make(map[string]any) 782 objValue := reflect.ValueOf(object) 783 objType := objValue.Type() 784 for index, num := 0, objType.NumField(); index < num; index++ { 785 field := objType.Field(index) 786 fieldValue := objValue.Field(index) 787 788 // 私有字段不处理 789 if IsPrivate(field.Name) { 790 continue 791 } 792 v := doObjectChange(reflect.TypeOf(fieldValue.Interface()), fieldValue.Interface()) 793 if v != nil { 794 resultMap[ToLowerFirstPrefix(field.Name)] = v 795 } 796 } 797 return resultMap 798 } else if objKind == reflect.Array || objKind == reflect.Slice { 799 // Array 结构 800 resultSlice := []any{} 801 objValue := reflect.ValueOf(object) 802 for index := 0; index < objValue.Len(); index++ { 803 arrayItemValue := objValue.Index(index) 804 805 v := doObjectChange(reflect.TypeOf(object).Elem(), arrayItemValue.Interface()) 806 if v != nil { 807 resultSlice = append(resultSlice, v) 808 } 809 } 810 return resultSlice 811 } 812 return nil 813 } 814 815 // ObjectToJson 对象转化为json,其中map对应的key大小写均可 816 func ObjectToJson(object any) string { 817 if object == nil || reflect.ValueOf(object).Kind() == reflect.Ptr { 818 return "{}" 819 } 820 821 // 只接收 map、struct、array、slice进行解析 822 objKind := reflect.ValueOf(object).Kind() 823 if objKind != reflect.Map && objKind != reflect.Struct && objKind != reflect.Array && objKind != reflect.Slice { 824 if objKind == reflect.String { 825 return ToString(object) 826 } 827 return "{}" 828 } 829 830 if objKind == reflect.Map { 831 // Map 结构 832 resultMap := make(map[string]any) 833 objValue := reflect.ValueOf(object) 834 if objValue.Len() == 0 { 835 return "{}" 836 } 837 838 for mapR := objValue.MapRange(); mapR.Next(); { 839 mapKey := mapR.Key() 840 mapValue := mapR.Value() 841 842 v := doObjectChange(reflect.TypeOf(mapValue.Interface()), mapValue.Interface()) 843 if v != nil { 844 resultMap[ToLowerFirstPrefix(ToString(mapKey.Interface()))] = v 845 } 846 } 847 return ToJsonString(resultMap) 848 } else if objKind == reflect.Struct { 849 // Struct 结构 850 resultMap := make(map[string]any) 851 objValue := reflect.ValueOf(object) 852 objType := objValue.Type() 853 for index, num := 0, objType.NumField(); index < num; index++ { 854 field := objType.Field(index) 855 fieldValue := objValue.Field(index) 856 857 // 私有字段不处理 858 if IsPrivate(field.Name) { 859 continue 860 } 861 v := doObjectChange(reflect.TypeOf(fieldValue.Interface()), fieldValue.Interface()) 862 if v != nil { 863 resultMap[ToLowerFirstPrefix(field.Name)] = v 864 } 865 } 866 return ToJsonString(resultMap) 867 } else if objKind == reflect.Array || objKind == reflect.Slice { 868 // Array 结构 869 resultSlice := []any{} 870 objValue := reflect.ValueOf(object) 871 for index := 0; index < objValue.Len(); index++ { 872 arrayItemValue := objValue.Index(index) 873 874 v := doObjectChange(reflect.TypeOf(object).Elem(), arrayItemValue.Interface()) 875 if v != nil { 876 resultSlice = append(resultSlice, v) 877 } 878 } 879 return ToJsonString(resultSlice) 880 } 881 return "{}" 882 } 883 884 // 转换为对应类型 885 // 886 // 符号数字类型 -> int 887 // 无符号类型 -> uint 888 // float类型 -> float 889 // complex128类型 -> complex128 890 // boole类型 -> bool 891 // string类型 -> string 892 // 集合/分片类型 -> [xx];其中xx对应的类型集合中的对象再次进行转换 893 // 结构体 -> 转换为map 894 // map -> 转换为map 895 func doObjectChange(objType reflect.Type, object any) any { 896 if objType == nil || object == nil { 897 return nil 898 } 899 objKind := objType.Kind() 900 if objKind == reflect.Ptr { 901 objKind = objType.Elem().Kind() 902 objValue := reflect.ValueOf(object) 903 return doObjectChange(objType.Elem(), objValue.Elem().Interface()) 904 } 905 if objKind == reflect.Int || objKind == reflect.Int8 || objKind == reflect.Int16 || objKind == reflect.Int32 || objKind == reflect.Int64 { 906 return ToInt64(object) 907 } else if objKind == reflect.Uint || objKind == reflect.Uint8 || objKind == reflect.Uint16 || objKind == reflect.Uint32 || objKind == reflect.Uint64 { 908 return ToUInt64(object) 909 } else if objKind == reflect.Float32 || objKind == reflect.Float64 { 910 return ToFloat64(object) 911 } else if objKind == reflect.Complex64 { 912 return ToString(object) 913 } else if objKind == reflect.Complex128 { 914 return ToString(object) 915 } else if objKind == reflect.Bool { 916 return ToBool(object) 917 } else if objKind == reflect.String { 918 return ToString(object) 919 } else if objKind == reflect.Array || objKind == reflect.Slice { 920 resultSlice := []any{} 921 objValue := reflect.ValueOf(object) 922 for index := 0; index < objValue.Len(); index++ { 923 arrayItemValue := objValue.Index(index) 924 925 v := doObjectChange(reflect.TypeOf(object).Elem(), arrayItemValue.Interface()) 926 if v != nil { 927 resultSlice = append(resultSlice, v) 928 } 929 } 930 return resultSlice 931 } else if objKind == reflect.Struct { 932 resultMap := make(map[string]any) 933 objValue := reflect.ValueOf(object) 934 objType := objValue.Type() 935 for index, num := 0, objType.NumField(); index < num; index++ { 936 field := objType.Field(index) 937 fieldValue := objValue.Field(index) 938 939 // 私有字段不处理 940 if IsPrivate(field.Name) { 941 continue 942 } 943 v := doObjectChange(reflect.TypeOf(fieldValue.Interface()), fieldValue.Interface()) 944 if v != nil { 945 resultMap[ToLowerFirstPrefix(field.Name)] = v 946 } 947 } 948 return resultMap 949 } else if objKind == reflect.Map { 950 resultMap := make(map[string]any) 951 objValue := reflect.ValueOf(object) 952 if objValue.Len() == 0 { 953 return nil 954 } 955 956 for mapR := objValue.MapRange(); mapR.Next(); { 957 mapKey := mapR.Key() 958 mapValue := mapR.Value() 959 960 v := doObjectChange(reflect.TypeOf(mapValue.Interface()), mapValue.Interface()) 961 if v != nil { 962 resultMap[ToLowerFirstPrefix(ToString(mapKey.Interface()))] = v 963 } 964 } 965 return resultMap 966 } else if objKind == reflect.Interface { 967 return ObjectToData(object) 968 } 969 return nil 970 } 971 972 func getValueFromMapValue(keyValues reflect.Value, key string) (reflect.Value, bool) { 973 if key == "" { 974 return reflect.ValueOf(nil), false 975 } 976 if keyValues.Kind() == reflect.Map { 977 if v1 := keyValues.MapIndex(reflect.ValueOf(key)); v1.IsValid() { 978 return v1, true 979 } else if v2 := keyValues.MapIndex(reflect.ValueOf(ToLowerFirstPrefix(key))); v2.IsValid() { 980 return v2, true 981 } 982 } else if keyValues.Kind() == reflect.Struct { 983 if v1 := keyValues.FieldByName(key); v1.IsValid() { 984 return v1, true 985 } else if v2 := keyValues.FieldByName(ToLowerFirstPrefix(key)); v2.IsValid() { 986 return v2, true 987 } 988 } 989 990 return reflect.ValueOf(nil), false 991 } 992 993 func IsPublic(s string) bool { 994 return isStartUpper(s) 995 } 996 997 func IsPrivate(s string) bool { 998 return isStartLower(s) 999 } 1000 1001 // 判断首字母是否大写 1002 func isStartUpper(s string) bool { 1003 return unicode.IsUpper([]rune(s)[0]) 1004 } 1005 1006 // 判断首字母是否小写 1007 func isStartLower(s string) bool { 1008 return unicode.IsLower([]rune(s)[0]) 1009 } 1010 1011 // ToLowerFirstPrefix 首字母小写 1012 func ToLowerFirstPrefix(dataStr string) string { 1013 return strings.ToLower(dataStr[:1]) + dataStr[1:] 1014 } 1015 1016 // ToUpperFirstPrefix 首字母大写 1017 func ToUpperFirstPrefix(dataStr string) string { 1018 return strings.ToLower(dataStr[:1]) + dataStr[1:] 1019 }