[Go]当把json解析到interface{}时 , 对应的真正类型

如果解析json时 , 把json解析到map[string]interface  , 那值所对应的真正类型是下面这样的

bool, for JSON booleans
float64, for JSON numbers
string, for JSON strings
[]interface{}, for JSON arrays
map[string]interface{}, for JSON objects
nil for JSON null

 

json中的数值类型 , 会是float64类型 

json对象会解析成 , map[string]interface

 

代码可以这样写:

func send(w http.ResponseWriter, r *http.Request){
    w.Header().Set("content-type", "text/json;charset=utf-8;")
    var sendData map[string]interface{}
    bodyBytes,err:=ioutil.ReadAll(r.Body)
    if err!=nil{
        msg, _ := json.Marshal(tools.JsonResult{Code: 400, Msg: "操作失败,"+err.Error()})
        w.Write(msg)
        return
    }

    err = json.Unmarshal(bodyBytes, &sendData)
    if err!=nil{
        msg, _ := json.Marshal(tools.JsonResult{Code: 400, Msg: "操作失败,"+err.Error()})
        w.Write(msg)
        return
    }

    smtpServer:=sendData["smtp"].(string)
    smtpFrom:=sendData["from"].(string)
    msg, _ := json.Marshal(tools.JsonResult{Code: 200, Msg: smtpServer+smtpFrom})
    w.Write(msg)
}

 

posted @ 2020-05-25 19:28  唯一客服系统开发笔记  阅读(3234)  评论(0编辑  收藏  举报