当前位置:网站首页>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
边栏推荐
- How to add logs to debug anr problems
- Leetcode56. consolidation interval
- LeetCode1114. Print in sequence
- Figure neural network can also be used as CV backbone model. Huawei Noah Vig architecture is comparable to CNN and transformer
- Lumiprobe non fluorescent alkyne research - dbco NHS ester
- The further application of Li Kou tree
- LeetCode116. 填充每个节点的下一个右侧节点指针
- Embedded dynamic Arabic string conversion LCD display string [thanks for Jianguo ambition]
- Definition and precautions of genuine St link/v2 j-link jtag/swd pin
- Globalsign's Pan domain SSL certificate
猜你喜欢

Anti rabbit dylight 488 abbkine universal immunofluorescence (if) toolbox

题解 Pie(POJ3122)超详细易懂的二分入门

What is an interface? What is interface testing?

PHP uses stack to solve maze problem

17 `bs object Node name h3 Parent ` parents get parent node ancestor node

Recommend two high-quality Wallpaper software

接口测试流程

Alist+raidrive gives the computer a complete 8billion GB hard disk drive

接口用例设计

Interface use case design
随机推荐
LeetCode1114. Print in sequence
Biovendor free light chain( κ and λ) Test steps of ELISA Kit
Which is the most reliable and safe for a securities company to open an account
Building web automation environment
Anti rabbit dylight 488 abbkine universal immunofluorescence (if) toolbox
二叉树类题目 力扣
券商公司开户哪个最靠谱最安全呢
LeetCode每日一题——522. 最长特殊序列 II
Understanding web automated testing
SqlTransaction
Definition and precautions of genuine St link/v2 j-link jtag/swd pin
Recommend two high-quality Wallpaper software
Web automation tool selection
Application of Andy s first dictionary (uva10815) Purple Book p112set
Is it safe to open a dig money account? Is it reliable?
题解 The SetStack Computer(UVa12096)紫书P116STL的综合应用
Which software is safer to open an account on and what is the account opening process?
Globalsign's Pan domain SSL certificate
[Note: analog MOS integrated circuit] bandgap reference (basic principle + current mode + voltage mode circuit explanation)
什么是接口?什么是接口测试?