查看: 12|回复: 0

Golang实现结构体和Json格式数据之间的互相转换

[复制链接]

0

主题

1

回帖

0

积分

积极分子

金币
1
阅读权限
220
精华
0
威望
0
贡献
0
在线时间
0 小时
注册时间
2008-6-9
发表于 2025-12-18 09:21:19 | 显示全部楼层 |阅读模式

摘要

本节主要学习Golang结构体和JSON序列化数据的转换命令。

1. 结构体到json格式

1.1 简单转换

Golang结构体转换成JSON格式数据,主要在结构体的相关字段中加入json : "keyword"字段。具体做法如下:

type Structname struct{
	feild1 Type1 `json:"keyword1"`
	feild2 Type2 `json:"keyword2"`
}

相关具体实例如下:

package message

import (
	"encoding/json"
	"log"
	"testing"
)

type Information struct{
	Name string `json:"name"`
	Addr string `json:"addr"`
}

func TestStructure(t *testing.T){
	var inf Information
	inf.Name="Alice"
	inf.Addr="Green Street"
	data,err:=json.Marshal(inf)
	if err!=nil{
		panic(err)
	}
	log.Println(string(data))
}

1.2 递归转换

为了转换一个嵌套结构体为JSON格式文件,首先在需要转换的结构体中构建json:"keyword"字段,其次,构建一个嵌套的Golang结构体,最后利用Json.Marshal函数进行转换。

package message

import (
	"encoding/json"
	"errors"
	"log"
	"testing"
)

type Employee struct {
	Position string `json:"position"`
	Name     Name   `json:"name"`
}

type Name struct {
	FirstName string `json:"firstname"`
	Surname   string `json:"surname"`
}

func TestStructure(t *testing.T){
	name:=Name{FirstName:"Zhang",Surname:"san"}
	employee:=Employee{Position:"China",Name: name}
	person,err:=json.Marshal(employee)
	if err!=nil{
		panic(errors.New("Wrong Converting behavior"))
	}
	log.Println(string(person))
}

2. json格式到结构体

2.1 简单转换

JSON格式数据转换为Golang结构体的过程,利用Json.Ummarshal函数进行转换,具体转换例子如下:

package message

import (
	"encoding/json"
	"log"
	"testing"
)

type Information struct{
	Name string `json:"name"`
	Addr string `json:"addr"`
}

func TestStructure(t *testing.T){
	alice:="{\"name\":\"Alice\",\"addr\":\"Green Street\"}"
	inf:=new(Information)
	err:=json.Unmarshal([]byte(alice),inf)
	if err!=nil{
		panic(err)
	}
	log.Println(inf)
}

2.2 嵌套JSON格式数据转换

类似于嵌套结构体转换到JSON格式的过程,从JSON格式数据转换到嵌套结构体数据的过程,就是首先构建嵌套JSON格式数据,其次通过Json.Ummarshal函数转换为嵌套结构体数据。

package message

import (
	"encoding/json"
	"log"
	"testing"
)

type Employee struct {
	Position string `json:"position"`
	Name     Name   `json:"name"`
}

type Name struct {
	FirstName string `json:"firstname"`
	Surname   string `json:"surname"`
}

func TestStructure(t *testing.T){
	str:="{\"position\":\"China\",\"name\":{\"firstname\":\"Zhang\",\"surname\":\"san\"}}"
	person1:=new(Employee)
	json.Unmarshal([]byte(str),person1)
	log.Println(person1,person1.Name)
}

以上就是JSon格式数据和Golang结构体之间的数据转换过程。

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

相关侵权、举报、投诉及建议等,请发 E-mail:qiongdian@foxmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部