Esempio n. 1
0
//转换为JSON.Type
func Parse(data interface{}) Type {
	var output Type

	real := reflect.Indirect(reflect.ValueOf(data))
	t := reflect.TypeOf(real)

	switch t.Kind() {
	case reflect.Struct, reflect.String, reflect.Slice:
		ParseToStruct(data, &output)
	case reflect.Map:
		if t.Name() == "Type" {
			return data.(Type)
		}
		output := make(Type)
		x := reflect.ValueOf(data)
		for _, v := range x.MapKeys() {
			var key string
			switch v.Type().Kind() {
			case reflect.String:
				key = v.String()
			case reflect.Struct:
				if m := utils.CallMethod(v.Interface(), "String"); m != nil {
					key = m.(string)
				}
			}
			if key != "" {
				output[key] = x.MapIndex(v).Interface()
			}
		}
		return output
	}
	return output
}
Esempio n. 2
0
func Error(args ...interface{}) JSON.Type {
	res := make(JSON.Type)
	res["code"] = "error"

	length := len(args)

	Map(args, func(key, msg interface{}) bool {
		index := key.(int)
		if msg == nil {
			return false
		}
		t := reflect.Indirect(reflect.ValueOf(msg)).Interface()
		kind := reflect.TypeOf(t).Kind()

		if index == 0 && reflect.TypeOf(msg).Name() == "ErrorType" {
			res["type"] = msg
			return false
		}

		switch kind {
		case reflect.Slice, reflect.Map:
			if index == 1 || length == 1 {
				res["result"] = msg
			}
		case reflect.String:
			if index == 0 {
				res["message"] = msg
			}
		case reflect.Ptr, reflect.Struct:
			if index == 1 || length == 1 {
				if d := utils.CallMethod(msg, "Error").(string); d != "" {
					res["message"] = d
				} else {
					res["result"] = msg
				}
			} else {
				res["result"] = msg
			}
		}
		return false
	})
	return res
}