用Gox语言进行JSON编码与解码-GX19.1

在Gox语言中进行JSON的编码和解码还是比较方便的,有多种方法可以选择,我们来看看。

先看看对JSON字符串的解码。


jsonStrT = `{"name": "Peter", "age": 19, "father": {"name": "Jordan", "age": 56}}`

println("jsonStrT:", jsonStrT)

println("\n---\n")

outT, errT = encoding_json.Unmarshal([]byte(jsonStrT))

if errT != nil {

	println("invald JSON:", errT)

	return

}

println("result:", outT)

println("name:", outT.name)

println("age:", outT.age)

println("father:", outT.father)

运行结果是:

jsonStrT: {"name": "Peter", "age": 19, "father": {"name": "Jordan", "age": 56}}

---

result: map[age:19 father:map[age:56 name:Jordan] name:Peter]
name: Peter
age: 19
father: map[age:56 name:Jordan]

这是用Go语言标准库中的JSON包进行解码的示例。可以看出,成功的解码出了映射类型的数据,其中还有嵌套映射,用Gox语言的语法访问其中的各个成员也都没有问题。

需要注意几点:

  • 注意Gox内置了很多常用的包,直接引用即可,无需声明或者import,例如本例中用到的Go语言标准库中的encoding/json包;
  • 调用Go语言官方标准库的encoding/json包进行解码,由于是多级包名,要按照Gox语言的约定,使用下划线代替斜杠字符,即用encoding_json表示encoding/json包;其他标准库的包也遵循此原则;
  • 为了方便,Unmarshal函数略微做了修改,无需传引用进去,直接用多返回值来传出结果;

下面是用tk包中的解码函数进行解码的例子。

jsonStrT = `{"name": "Peter", "age": 19, "father": {"name": "Jordan", "age": 56}}`
println("jsonStrT:", jsonStrT)
println("\n---\n")

outT, errT = tk.FromJSON(jsonStrT)

if errT != nil {
	println("invald JSON:", errT)
	return
}

println("result:", outT)

println("name:", outT.name)
println("age:", outT.age)
println("father:", outT.father)

运行结果为:

jsonStrT: {"name": "Peter", "age": 19, "father": {"name": "Jordan", "age": 56}}

---

jsonStrT: {"name": "Peter", "age": 19, "father": {"name": "Jordan", "age": 56}}

---

result: map[age:19 father:map[age:56 name:Jordan] name:Peter]
name: Peter
age: 19
father: map[age:56 name:Jordan]

效果与标准库的类似,理论上速度会更快一些。注意,tk包是Gox语言中唯一无需用全路径引用的包,这是因为tk包的使用率太高了,很多常用函数事实上基本所有代码中都大概率会用到,如果写全了要写“github_topxeq_tk”,太麻烦了。

下面再看看如何进行JSON编码。

// convert object to JSON string
appleT = {
	"Type": "apple",
	"Color": "Red红的",
	"Weight重量": 10,
	"canEat": true,
	"Ingredients" : [
		{
			"Name": "Protein",
			"Amount": 0.3,
		},
		{
			"Name": "Sugar糖分",
			"Amount": 10.4,
		},
	],
}

pv("appleT")
println("\n---\n")

newJSONT, errT = tk.ToJSON(appleT)

if errT != nil {
	println("failed to generate JSON:", errT)
	return
}

pl("JSON: %v", newJSONT)

// get indented JSON string
newJSONIndentT, errT = tk.ToJSONIndent(appleT)

if errT != nil {
	println("failed to generate JSON:", errT)
	return
}

println("\n---\n")

pl("Indented JSON: %v", newJSONIndentT)


这段代码中定义了一个appleT变量,包含一个复杂的结构体数据,分别使用tk.ToJSON和ToJSONIndent函数格式化后结果如下:

appleT(map[string]interface {}): map[Color:Red红的 Ingredients:[map[Amount:0.3 Name:Protein] map[Amount:10.4 Name:Sugar糖分]] Type:ap
ple Weight重量:10 canEat:true]

---

JSON: {"Ingredients":[{"Name":"Protein","Amount":0.3},{"Name":"Sugar糖分","Amount":10.4}],"Type":"apple","Color":"Red红的","Weight重
量":10,"canEat":true}

---

Indented JSON: {
  "Type": "apple",
  "Color": "Red红的",
  "Weight重量": 10,
  "canEat": true,
  "Ingredients": [
    {
      "Name": "Protein",
      "Amount": 0.3
    },
    {
      "Name": "Sugar糖分",
      "Amount": 10.4
    }
  ]
}

效果还是不错的,其中,tk.ToJSONIndent是对生成的JSON做了缩进处理,让它看起来更美观一些。

如果想要仅从JSON文本中解析出一部分数据,可以用下面的方法:

appleT = {
	"Type": "apple",
	"Color": "Red",
	"Weight": 10,
	"canEat": true,
	"Ingredients" : [
		{
			"Name": "Protein",
			"Amount": 0.3,
		},
		{
			"Name": "Sugar",
			"Amount": 10.4,
		},
	],
}

pv("appleT")
println("\n---\n")

newJSONT, errT = tk.ToJSON(appleT)

if errT != nil {
	println("failed to generate JSON:", errT)
	return
}

pl("JSON: %v", newJSONT)

println("\n---\n")

nodeT = tk.GetJSONNode(newJSONT, "Color")
pv("nodeT")

println("\n---\n")

node1T = tk.GetJSONNode(newJSONT, "canEat")
pv("node1T")

println("\n---\n")

node2T = tk.GetJSONNodeAny(newJSONT, "Ingredients")
pl("Value type: %v", node2T.ValueType())

println("\n---\n")

pv("node2T")

subNode1T = tk.GetJSONSubNode(node2T, 0, "Name")

println("\n---\n")

pv("subNode1T")

subNode2T = tk.GetJSONNode(newJSONT, "Ingredients", 1, "Amount")

println("\n---\n")
pv("subNode2T")

subNode3T = tk.GetJSONNode(newJSONT, "Ingredients", "*")

println("\n---\n")
pv("subNode3T")

subSubNodeT = tk.GetJSONSubNode(subNode3T[0], "Name")

println("\n---\n")
pv("subSubNodeT")

subNode4T = tk.GetJSONNodeAny(newJSONT, "Ingredients", 3, "Name")

println("\n---\n")
pv("subNode4T")

pl("Value type: %v", subNode4T.ValueType())

pl("Last Error: %v", subNode4T.LastError())

运行结果是:

appleT(map[string]interface {}): map[Color:Red Ingredients:[map[Amount:0.3 Name:Protein] map[Amount:10.4 Name:Sugar]] Type:apple Weight:10 canEat:true]

---

JSON: {"Type":"apple","Color":"Red","Weight":10,"canEat":true,"Ingredients":[{"Name":"Protein","Amount":0.3},{"Name":"Sugar","Amount":10.4}]}

---

nodeT(string): Red

---

node1T(bool): true

---

Value type: 5

---

node2T(*jsoniter.arrayLazyAny): &{
   
   {} 0xc00040c000 [91 123 34 78 97 109 101 34 58 34 80 114 111 116 101 105 110 34 44 34 65 109 111 117 110 116 34 58 48 46 51 125 44 123 34 78 97 109 101 34 58 34 83 117 103 97 114 34 44 34 65 109 111 117 110 116 34 58 49 48 46 52 125 93] <nil>}

---

subNode1T(string): Protein

---

subNode2T(float64): 10.4

---

subNode3T([]jsoniter.Any): [0xc000646300 0xc000646330]

---

subSubNodeT(string): Protein

---

subNode4T(*jsoniter.invalidAny): &{
   
   {} 0xc000156810}
Value type: 0
Last Error: [3 Name] not found

这段代码中,从newJSONT这个JSON文本中,用 tk.GetJSONNode函数可以直接从文本中获取各种类型的数据,其中nodeT是字符串类型的,node1T是布尔类型的。复杂类型的数据可以用tk.GetJSONNodeAny来获取,然后返回的节点对象可以进一步处理,例如用tk.GetJSONSubNode函数来获取它的子节点。

这些函数中,除了第一个参数是JSON文本或节点对象外,后面都是可以有任意多个参数,表示需要获取节点的路径,例如本例中的subNode2T,就是获取整个JSON文本转换成对象后,其中的Ingredients节点下的索引为1(也就是第2个)子节点的Amount子节点的数据,在这里是10.4这个数字。

如果路径错误的话,可以通过获取节点对象的类型(通过ValueType函数),如果是0则为invalid即无效的。此时获取该节点对象的LastError函数的返回值即为错误原因。

另外,可以看出,即使是Go语言中默认不导出的小写字母开头的字段,用这种方法也可以正常导出(本例中的canEat)。前面的tk.ToJSON等函数也是会将小写字母开头的字段编码进JSON的,因此一般不建议使用Go语言标准库中的JSON编解码函数,推荐使用tk库中的JSON编解码函数。

猜你喜欢

转载自blog.csdn.net/weixin_41462458/article/details/108020473