亲宝软件园·资讯

展开

Golang interface转string Golang 实现interface类型转string类型

一条小码农 人气:0
想了解Golang 实现interface类型转string类型的相关内容吗,一条小码农在本文为您仔细讲解Golang interface转string的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Golang,interface转string,interface类型,string类型,下面大家一起来学习吧。

看代码吧~

// Strval 获取变量的字符串值
// 浮点型 3.0将会转换成字符串3, "3"
// 非数值或字符类型的变量将会被转换成JSON格式字符串
func Strval(value interface{}) string {
	var key string
	if value == nil {
		return key
	}
	switch value.(type) {
	case float64:
		ft := value.(float64)
		key = strconv.FormatFloat(ft, 'f', -1, 64)
	case float32:
		ft := value.(float32)
		key = strconv.FormatFloat(float64(ft), 'f', -1, 64)
	case int:
		it := value.(int)
		key = strconv.Itoa(it)
	case uint:
		it := value.(uint)
		key = strconv.Itoa(int(it))
	case int8:
		it := value.(int8)
		key = strconv.Itoa(int(it))
	case uint8:
		it := value.(uint8)
		key = strconv.Itoa(int(it))
	case int16:
		it := value.(int16)
		key = strconv.Itoa(int(it))
	case uint16:
		it := value.(uint16)
		key = strconv.Itoa(int(it))
	case int32:
		it := value.(int32)
		key = strconv.Itoa(int(it))
	case uint32:
		it := value.(uint32)
		key = strconv.Itoa(int(it))
	case int64:
		it := value.(int64)
		key = strconv.FormatInt(it, 10)
	case uint64:
		it := value.(uint64)
		key = strconv.FormatUint(it, 10)
	case string:
		key = value.(string)
	case []byte:
		key = string(value.([]byte))
	default:
		newValue, _ := json.Marshal(value)
		key = string(newValue)
	}
	return key
}

补充:golang json 为map[string] interface{}

json字符串:

{"sn":1,"ls":false,"bg":0,"ed":0,"ws":[{"bg":0,"cw":[{"sc":0,"w":"还"}]},{"bg":0,"cw":[{"sc":0,"w":"有点"}]},{"bg":0,"cw":[{"sc":0,"w":"眼熟"}]}]}

需要将json格式中的w字段取出来,并且拼成结果串进行展示

1、从json数组中获取ws

2、ws是数组,数组元素为object

3、cw是数组,数组元素为object

4、w是string

5、从cw遍历获取w字段

解析代码:

func RecResultJsonToPlain() {
    var recResult string
    var dat map[string]interface{}
    json.Unmarshal([]byte(json_str), &dat)
 
    if v, ok := dat["ws"]; ok {
        ws := v.([]interface{})
        for i, wsItem := range ws {
            wsMap := wsItem.(map[string]interface{})
            if vCw, ok := wsMap["cw"]; ok {
                cw := vCw.([]interface{})
                for i, cwItem := range cw {
                    cwItemMap := cwItem.(map[string]interface{})
                    if w, ok := cwItemMap["w"]; ok {
                        recResult = recResult + w.(string)
                    }
                }
            }
        }
    }
    fmt.Println(recResult)
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方,望不吝赐教。

加载全部内容

相关教程
猜你喜欢
用户评论