Go 中 JSON 的序列化和反序列化

golang中对json的序列化/反序列化操作还是比较容易的,
序列化操作主要是通过encoding/json包的Marshal()方法来实现,
反序列化操作主要是通过encoding/json包的Unmarshal()方法来实现.

1//JSON序列化和反序列化 2 3//可用在api序列化输出 4//转成结构体,方便程序操作等 5 6package main 7 8import ( 9 "encoding/json" 10 "fmt" 11) 12 13type Response1 struct { 14 Page int 15 Fruits []string 16} 17 18type Response2 struct { 19 Page int `json:"page"` 20 Fruits []string `json:"fruits"` 21} 22 23func main() { 24 25 //布尔型 26 boolByte, _ := json.Marshal(true) 27 fmt.Println(string(boolByte)) 28 29 //整数型 30 intByte, _ := json.Marshal(100) 31 fmt.Println(string(intByte)) 32 33 //浮点型 34 floatByte, _ := json.Marshal(1.23456) 35 fmt.Println(string(floatByte)) 36 37 //字符串 38 stringByte, _ := json.Marshal("字符串啊啊啊") 39 fmt.Println(string(stringByte)) 40 41 //切片 42 sliceByte, _ := json.Marshal([]string{"apple", "orange", "banana"}) 43 fmt.Println(string(sliceByte)) 44 45 //字典 46 mapByte, _ := json.Marshal(map[string]int{"apple": 5, "orange": 6, "banana": 7}) 47 fmt.Println(string(mapByte)) 48 49 //自定义类型1 50 customsByte1, _ := json.Marshal(&Response1{Page: 1, Fruits: []string{"apple", "orange", "banana"}}) 51 fmt.Println(string(customsByte1)) 52 53 //自定义类型2,tag语法 54 customsByte2, _ := json.Marshal(&Response2{Page: 2, Fruits: []string{"apple", "orange", "banana"}}) 55 fmt.Println(string(customsByte2)) 56 57 //反序列化到结构体 58 json1 := `{"Page":1,"Fruits":["apple","orange","banana"]}` 59 json2 := `{"page":2,"fruits":["apple","orange","banana"]}` 60 response1 := Response1{} 61 response2 := Response2{} 62 json.Unmarshal([]byte(json1), &response1) 63 fmt.Println(response1) 64 json.Unmarshal([]byte(json2), &response2) 65 fmt.Println(response2) 66}
点赞
收藏

评论区

加载中...

相关推荐

java中的序列化方式及dubbo使用kryo序列化

java中的序列化方式:1\.自带序列化 ObjectInputSteam、ObjectOutStream等2\.hession23\.json,xml等格式4.kryo5.FST\dubbo直接多种序列化方式,默认是hession2.比较成熟,但是效率略低。可以配置使用kryo  <dubbo:

FastJson、Jackson、Gson进行Java对象转换Json的细节处理

Java对象转换Json的细节处理前言Java对象在转json的时候,如果对象里面有属性值为null的话,那么在json序列化的时候要不要序列出来呢?对比以下json转换方式一、fastJson1、fastJson在转换java对象为json的时候,默认是不序列化nu

C# JToken类的使用,实现解析动态json数据、遍历、查找

在原来解析json数据是,一般都是用反序列化来实现json数据的解读,这需要首先知道json数据的结构并且建立相应的类才能反序列化,一旦遇到动态的json数据,这种方法就不使用。为了解决动态解析json数据,微软有个Newtonsoft.Json封装类十分好用,里面的JToken直接实现ling查询。将json字符串解析为JToken,

Json解析工具 @JsonIgnore 注解的使用

@JsonIgnoreProperties        此注解是类注解,作用是json序列化时将javabean中的一些属性忽略掉,序列化和反序列化都受影响。@JsonIgnore        此注解用于属性或者方法上(最好是属性上),作用和上面的@JsonIgnoreProperties一样。@JsonFo

Fastjson API Stream使用说明

FastjsonAPIStreamFastjson当需要处理超大JSON文本时,需要StreamAPI,在fastjson1.1.32版本中开始提供StreamAPI。如何序列化超大JSON数组序列化如果你的JSON格式是一个巨大的JSON数组,有很多元素,

Django 前台通过json 取出后台数据

前台通过json取出后台数据步骤1:后台数据通过JSON序列化成字符串注意:1、json是1个字符串     2、通过json.dumps('xxx')序列化成1个字符串的 '字典对象' views.pydefajax(request):ifrequest.