//需求:按照RequestBody key顺序排序. 格式化输出:[{content=测试模板文本内容,exType=txt,sort=1,type=text}], key和value用=号连接,值保持不变。用strings.Replace的做法是不严谨的。
package main
import (
"fmt"
)
type RequestBody struct {
Content string `json:"content"`
ExType string `json:"exType"`
Sort int `json:"sort"`
Type string `json:"type"`
ContentType string `json:"contentType,omitempty"`
}
sourceData :=`[{"content":"测试模板文本内容","exType":"txt","sort":1,"type":"text"}]`
func Convert(sourceData string ) string {
var mapData []map[string]interface{}
var allRequestBody string
var keyList []string
jsonRequestData,_ := json.Marshal(sourceData)
if er := json.Unmarshal(jsonRequestData, &mapData); er != nil {
fmt.Println("json.Unmarshal failed",er)
return allRequestBody
}
for _, v := range mapData {
var tmpData map[string]interface{}
jsonbodyData,_ := json.Marshal(v)
if er := json.Unmarshal(jsonbodyData, &tmpData); er != nil {
fmt.Println("json.Unmarshal jsonBodyData failed" er)
return allRequestBody
}
for data := range tmpData {
keyList = append(keyList, data)
}
sort.Strings(keyList)
for _,v := range keyList {
resultList = append(resultList, fmt.Sprintf("%s=%s",v,fmt.Sprint(tmpData[v])))
}
sort.Strings(resultList)
//这里转不了map[string]interface{}
return strings.Join(resultList, ",")
}
return ""
}
[{content=测试模板文本内容,exType=txt,sort=1,type=text}] 这个里面的数据类型不知道怎么表示,interface{} ?
#1
更多评论