一.go语言 struct json相互转换

1.Go语言自带JSON转换库  encoding/json

2.把对象转换为json的方法为 json.Marshal(),其函数原型为:

func Marshal(v interface{}) ([]byte, error) {
   e := newEncodeState()

   err := e.marshal(v, encOpts{escapeHTML: true})
   if err != nil {
      return nil, err
   }
   buf := append([]byte(nil), e.Bytes()...)

   e.Reset()
   encodeStatePool.Put(e)

   return buf, nil
}

1)   函数可以接收任意类型的数据 v,并转换为字节数组类型,返回值就是json数据和错误代码;若转换成功,则err = nil;
2)在进行对象转换为JSON的过程中,会遵循一下几条原则:
  1.布尔型转换为JSON后仍然是布尔型;
  2.浮点型转换为JSON后里面的常规数字;
  3.字符串将以UTF-8编码转化输出为Unicode字符串,将特殊字符转义;
  4.数组和切片被转换为JSON里面的数组,[]byte类会被转换为base64编码后的字符串,slice的零值被转换为null;
  5.结构体转换为JSON对象,并且只有结构体内变量必须首字母大写,才可被导出的字段转化输出,而且这些字段会被作为JSON对象的字符串索引;
  6.转换一个map类型的数据结构时,该数据的类型必须时map[string]T,T可以是encoding/json包支持的任意类型。

2.把JSON转换回对象方法的方法为json.Unmarshal(),函数原型为:

func Unmarshal(data []byte, v interface{}) error {
   // Check for well-formedness.
   // Avoids filling out half a data structure
   // before discovering a JSON syntax error.
   var d decodeState
   err := checkValid(data, &d.scan)
   if err != nil {
      return err
   }

   d.init(data)
   return d.unmarshal(v)
}

 1)函数会把传入的data作为一个JSON来进行解析,解析后的数据存储在参数v中,这个参数可以是任意类型的参数(是一个类型的指针);

 2)json.Umarshal()函数会根据一个约定的顺序查找结构中的字段,如果找到一个即发生匹配。假设一个JSON对象有一个名为“Foo”的索引,要将“Foo”所对应的值填充到目标结构体的目标字段上,json.Umarshal()将会遵循如下顺序进行查找匹配:

  1.一个包含Foo标签的字段;

  2.一个名为Foo的字段

  3.一个名为Foo或者除了首字母不区分大小写的名为Foo的字段,这些字段在类型声明中必须都是首字母大写,可被导出字段。

  注意:如果JSON中的字段在Go目标类型中不存在,json,Umarshal()函数在解码过程中会丢弃该字段。

3)当JSON的结构位置时,会遵循一下规则:

  1.JSON中的布尔型将会转换为Go中的bool类型;

  2.数值将会被转换为Go的float64类型;

  3.字符串转换后是stirng类型;

  4.JSON数组将会转换为[]interface{}类型

  5.JSON对象会被转换为map[stirng]interface{}类型;

  6.null值会转换为nil

  注意:在Go的标准库中encoding/json包中,允许使用map[stirng]interface{}和interface{}类型来分别存储结构中的JSON对象和JSON数组。

4.遇到问题,解决问题

1)接收JSON字符串后,将其转换为结构体,JSON字符串中某一键值对,值类型为JSONArray,在结构体中声明为string。在转换之前将JSON中“properties”的值试图转换为string类型,最终失败;最终在结构体中修改该变量类型为[]interface{},转换成功。

{
	"subjectId":"MathOperation",
	"subjectName":"数学运算",
	"subjectDispSerial":2,
	"subjectClass":"principal",
	"activityId":"Sum",
	"actDispSerial":1,
	"icon":"Sum.png",
	"modiTime":"2017-06-13 10:17:17",
	"funcGrp":"arithmetic",
	"author":"",
	"status":2,
	"properties":[
		{"key":"nodeLabel","val":"","diapName":"节点标签","editStyle":"TextField","dispSerial":10,"editable":true},
		{"key":"subjectType","val":"数学运算","diapName":"所属类别","editStyle":"TextField","dispSerial":20,"editable":false},
		{"key":"nodeExplain","val":"","diapName":"节点说明","editStyle":"TextField","dispSerial":30,"editable":false},
		{"key":"inputType","val":"Double[]","diapName":"输入变量类型","editStyle":"ComboBox","dispSerial":40,"editable":true},
		{"key":"outputType","val":"Double[]","diapName":"输出变量类型","editStyle":"ComboBox","dispSerial":50,"editable":true},
		{"key":"note","val":"","diapName":"备注","editStyle":"PluginDialog","dispSerial":1000,"editable":true}
	],
	"inportInit":2,
	"inportMax":20,
	"outportInit":1,
	"outportMax":20,
	"topportInit":0,
	"topportMax":0,
	"bottomportInit":0,
	"bottomportMax":0,
	"note":""
}

  

type Activity struct {
	Id int
	SubjectId string
	SubjectName string
	SubjectDispSerial int
	SubjectClass string
	ActivityId string
	ActivityName string
	ActDispSerial int
	Icon string
	ModiTime string
	FuncGrp string
	Author string
	Status int
	Properties []interface{}
	InpotInit int
	InportMax int
	OutportInit int
	OutportMax int
	TopportInit int
	TopportMax int
	BottomportInit int
	BottomportMax int
	Note string
}
var act models.Activity

if err := json.Unmarshal([]byte(data), &act); err == nil {
	fmt.Println(act.SubjectId)
	fmt.Println(act.ActivityId)
	fmt.Println(act.Properties)

} else {
	fmt.Println(err)
}

  

  

  

猜你喜欢

转载自www.cnblogs.com/li-jing/p/10133619.html