最近想写一个将gorm model 转成普通struct的工具,通过gorm的tag和json 进行匹配赋值
现在我想问一下,怎么把time.Time类型的值获取到?
可能描述没有很清楚,看代码:
```
func CoverModelToStruct(model, dest interface{}) error {
v := reflect.ValueOf(dest).Elem()
if !v.CanAddr() {
return fmt.Errorf("must be a pointer")
}
m := reflect.ValueOf(model).Elem()
if !m.CanAddr() {
return fmt.Errorf("must be a pointer")
}
for i := 0; i < v.NumField(); i++ {
fieldDest := v.Type().Field(i)
tagJson := fieldDest.Tag.Get("json")
if tagJson == "" || tagJson == "-" {
continue
}
for j := 0; j < m.NumField(); j++ {
fieldModel := m.Type().Field(j)
tagGorm := fieldModel.Tag.Get("gorm")
tagGorm = getGormTag(tagGorm)
fmt.Println("aaaa", tagGorm, tagJson)
if tagGorm == tagJson {
fmt.Println("match")
value := m.FieldByName(fieldModel.Name)
kind := v.FieldByName(fieldDest.Name).Kind()
switch {
case kind == reflect.Int64, kind == reflect.Int, kind == reflect.Int8,
kind == reflect.Int16, kind == reflect.Int32:
{
fmt.Println("int")
fi := v.FieldByName(fieldDest.Name)
if !fi.CanSet() {
return fmt.Errorf("can not set value of:%s", fieldDest.Name)
}
fmt.Println("set done", value.Int())
fi.SetInt(value.Int())
}
case kind == reflect.String:
{
fi := v.FieldByName(fieldDest.Name)
if !fi.CanSet() {
return fmt.Errorf("can not set value of:%s", fieldDest.Name)
}
fi.SetString(value.String())
}
case kind == reflect.Bool:
{
fi := v.FieldByName(fieldDest.Name)
if !fi.CanSet() {
return fmt.Errorf("can not set value of:%s", fieldDest.Name)
}
fi.SetBool(value.Bool())
}
case kind == reflect.Float32, kind == reflect.Float64:
{
fi := v.FieldByName(fieldDest.Name)
if !fi.CanSet() {
return fmt.Errorf("can not set value of:%s", fieldDest.Name)
}
fi.SetFloat(value.Float())
}
case kind == reflect.Struct:
{ //time.Time类型会被识别成struct,我要取到这个struct里面的时间值付给dest
fmt.Println("time", kind)
}
default:
return fmt.Errorf("暂不支持%s类型", kind)
}
}
}
}
return nil
}
func getGormTag(gorm string) string {
if len(gorm) < 7 {
return ""
}
gorm = gorm[7:]
res := strings.Split(gorm, ";")
return res[0]
}
```
有疑问加站长微信联系(非本文作者)