当前位置:网站首页>Golang JSON serializing and deserializing strings deserializing to map[string]interface{}
Golang JSON serializing and deserializing strings deserializing to map[string]interface{}
2022-06-28 21:36:00 【Zen and the art of computer programming】
json.Unmarshl Deserialization : take json String to struct
func Unmarshal(data []byte, v interface{}) error demand : take json String to struct
1) Predefine json Corresponding structure type ;
2) call json.Unmarshl
func main() {
// The inverted quotation marks here indicate that you do not change your meaning , That is to say string type
resp := `{"code":0,"message":"success","grades":[{"gradeClass":" In grade one ","Score":{"chinese":99,"english":88}},{"gradeClass":" second grade ","Score":{"chinese":100,"english":98}}]}`
var stu Student
err := json.Unmarshal([]byte(resp), &stu)
if err != nil {
log.Println(err)
}
log.Println(stu)
// 2021/08/12 23:37:19 {0 success [{ In grade one {99 88}} { second grade {100 98}}]}
}
type Student struct {
Code int `json:"code"` // Use tag, Indicates correspondence json Field name
Message string `json:"message"`
Grades []GradeType `json:"grades"` // Structure class array
}
type GradeType struct {
GradeClass string `json:"gradeClass"`
Score ScoreType
}
type ScoreType struct {
Chinese int `json:"chinese"`
English int `json:"english"`
}json String is anti sequenced into map
// Strong go interface Type to string type ( Be careful : No convert.ToJSONString)
wordCloudJson := convert.ToString(data[0]["word_cloud_json"])
words := make(map[string]interface{})
err = json.Unmarshal([]byte(wordCloudJson), &words)
if err != nil {
logu.CtxError(ctx, error_code.ProcessError, "GetBrandWordCloud Unmarshal", "wordCloudJson:%v,error: %v", wordCloudJson, err)
return result, err
}
for k, v := range words {
result = append(result, &competition_detail.BrandWord{
ProductPropertyValue: k,
ProductFrequency: convert.ToInt64(v),
})
}
// Descending order TOP 100
top(&result, 100)among ,func ToString(i interface{}) string Code :
// ToString Strong go interface Type to string type
func ToString(i interface{}) string {
v, _ := ToStringE(i)
return v
}
// ToStringE Strong go interface Type to string, Support error return value
func ToStringE(i interface{}) (string, error) {
i = indirectToStringerOrError(i)
switch s := i.(type) {
case string:
return s, nil
case bool:
return strconv.FormatBool(s), nil
case float64:
return strconv.FormatFloat(s, 'f', -1, 64), nil
case float32:
return strconv.FormatFloat(float64(s), 'f', -1, 32), nil
case int:
return strconv.Itoa(s), nil
case int64:
return strconv.FormatInt(s, 10), nil
case int32:
return strconv.Itoa(int(s)), nil
case int16:
return strconv.FormatInt(int64(s), 10), nil
case int8:
return strconv.FormatInt(int64(s), 10), nil
case uint:
return strconv.FormatInt(int64(s), 10), nil
case uint64:
return strconv.FormatInt(int64(s), 10), nil
case uint32:
return strconv.FormatInt(int64(s), 10), nil
case uint16:
return strconv.FormatInt(int64(s), 10), nil
case uint8:
return strconv.FormatInt(int64(s), 10), nil
case []byte:
return string(s), nil
case template.HTML:
return string(s), nil
case template.URL:
return string(s), nil
case template.JS:
return string(s), nil
case template.CSS:
return string(s), nil
case template.HTMLAttr:
return string(s), nil
case nil:
return "", nil
case fmt.Stringer:
return s.String(), nil
case error:
return s.Error(), nil
default:
v := reflect.ValueOf(i)
if method, ok := reflect.TypeOf(i).MethodByName("String"); ok && method.Type.NumIn() == 0 &&
method.Type.NumOut() == 1 && method.Type.Out(0).Kind() == reflect.String {
return method.Func.Call([]reflect.Value{v})[0].String(), nil
}
switch v.Kind() {
case reflect.Func:
fullName := runtime.FuncForPC(v.Pointer()).Name()
ss := strings.Split(fullName, ".")
if len(ss) > 0 {
return ss[len(ss)-1], nil
} else {
return fullName, nil
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return ToStringE(v.Uint())
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return ToStringE(v.Int())
case reflect.Float64, reflect.Float32:
return ToStringE(v.Float())
case reflect.Bool:
return ToStringE(v.Bool())
case reflect.String:
return v.String(), nil
}
return "", fmt.Errorf("unable to cast %#v of type %T to string", i, i)
}
}Reference material
https://blog.csdn.net/Sunny_Future/article/details/119656822
边栏推荐
- QJsonObject的使用示例
- Web automation tool selection
- pyechart绘制多条y轴折线图
- 关于不完全类型的认识
- Microsoft's exclusive payment function has also been perfectly unlocked
- Flask——总结
- Anti rabbit dylight 488 abbkine universal immunofluorescence (if) toolbox
- Which software is safer to open an account on and what is the account opening process?
- GlobalSign的泛域名SSL证书
- [Note: circuit intégré MOS analogique] référence de bande Gap (principe de base + mode courant + circuit en mode tension)
猜你喜欢

PHP uses stack to solve maze problem

Pyechart drawing multiple Y-axis line graphs

16 `bs对象.节点名div.属性contents` children descendants 获取子节点 子孙节点
![[Note: circuit intégré MOS analogique] référence de bande Gap (principe de base + mode courant + circuit en mode tension)](/img/cd/be62272d465ca990456c222b38df67.png)
[Note: circuit intégré MOS analogique] référence de bande Gap (principe de base + mode courant + circuit en mode tension)
![[software test] 2022 national unified college enrollment examination](/img/9a/d76d7eb30a097d364fef28c2230e1a.png)
[software test] 2022 national unified college enrollment examination

postman简介与安装步骤

【激活函数】

Interface test process

User network model and QoE

Study on bifunctional crosslinker lumiprobe sulfoacyanine 7 dicarboxylic acid
随机推荐
Definition and precautions of genuine St link/v2 j-link jtag/swd pin
Understanding web automated testing
LeetCode116. Populate the next right node pointer for each node
[Note: circuit intégré MOS analogique] référence de bande Gap (principe de base + mode courant + circuit en mode tension)
图神经网络也能用作CV骨干模型,华为诺亚ViG架构媲美CNN、Transformer
【笔记:模拟MOS集成电路】带隙基准(基本原理+电流模+电压模电路详解)
LeetCode877. 石子游戏
LeetCode213. House raiding II
Openfire user and group relationship migration
Usage example of qjsonobject
Can you make money by speculating in stocks? It's safe to open an account
LeetCode123. 买卖股票的最佳时机III
17 `bs对象.节点名h3.parent` parents 获取父节点 祖先节点
Is the rapid SSL wildcard certificate genuine in 1981
Leetcode daily question - 324 Swing sort II
Application practice | 1billion data second level correlation. Huolala's OLAP System Evolution Based on Apache Doris (with PPT download)
Pie (poj3122) super detailed and easy to understand binary introduction
QStringLiteral(str)
After easycvr creates a new user, the video access page cannot be clicked. Fix the problem
LeetCode226. 翻转二叉树