当前位置:网站首页>Golang uses reflection to set items in the structure, JSON data source
Golang uses reflection to set items in the structure, JSON data source
2022-07-21 06:58:00 【It workers】
The project involves the need to dynamically modify the configuration , There are many types of dynamically set data items , The base type int/string There are reflect Native support for , How to deal with other types ?
What I think of here is : Other types are used uniformly json Inverse sequence , Then use reflection settings .
The sample code is as follows :
package main
import "fmt"
import "encoding/json"
import "reflect"
type Settings struct {
A int
B [][]int
}
func main() {
// Prepare simulation json data
var arr [][]int
arr = append(arr, []int{1, 2})
s, _ := json.Marshal(&arr)
// Simulate dynamic settings B term
var t Settings
key := "B"
tt := reflect.ValueOf(&t)
tv := tt.Elem().FieldByName(key)
fmt.Println("type:", tv.Type().String())
newObj := reflect.New(tv.Type())
err := json.Unmarshal(s, newObj.Interface())
if err != nil {
fmt.Println(err.Error())
}
tv.Set(newObj.Elem())
fmt.Println(t)
}
Here is mainly the penultimate line , take JSON The data obtained by deserialization newObj Set to tv when , A little trouble ,
*[][]int and [][]int The problem between . Later, I thought of using it Elem(), Problem solved . Empathy , It should be possible to dynamically set other custom types . Mainly right reflect The interface of is not proficient .
边栏推荐
- MySQL 啥时候用表锁,啥时候用行锁?
- Wallys/DR882/QCA9882/ AC/AN MiniPCIE/2×2.4GHz 2x5GHz MT7915 MT7975
- 将数据集转换为VOC格式
- [go open source treasure] performance tuning skills based on golang syntax (array traversal)
- What should EDI prepare for easy docking with Lloyd's Lowe's?
- Convert datasets to VOC format
- 亮点抢先看!2022 开放原子全球开源峰会定于 7 月 25-29 日在北京举办
- 元宇宙中DeFi的可能性和局限性
- IDEA手动编写Servlet详解
- 6-11漏洞利用-利用搭建环境发送邮件
猜你喜欢
Analyzing the internal mechanism and breakthrough path of "Web3 paradox"
报表设计工具FastReport Online Designer V2022.1新功能全剖析
IDEA手动编写Servlet详解
6-10漏洞利用-Smtp实验环境搭建
解析「Web3悖论」的内在机理与突破路径
(Note)CIE色度图
Tensorflow network model migration based on tensorflow gpu2ascend tool
霸榜MS MARCO!基于Transformer的混合列表感知排序模型
kvm虚拟化作业
数仓之数据质量建设
随机推荐
数字电源--第一章
图的基本定义和相关概念(一)
[the problem has been solved] - MySQL uses the same yaml and NFS shared storage to report an error
Golang利用反射设置结构体中的项, Json数据源
关于父进程和子进程的关系(UAC 绕过思路)
General GUI large disk based on MCU
DAO的精简化治理的委托机制
xts performance auto fix script
PostgreSQL中按时间月份自动创建分区表
Possibilities and limitations of defi in the metauniverse
opencv 基本操作
鸿蒙HarmonyOS 3官宣:7月27日正式发布;苹果2023年放缓部分团队招聘和支出;俄罗斯对谷歌重罚26亿元|极客头条...
Convert datasets to VOC format
解析「Web3悖论」的内在机理与突破路径
How to handle exceptions when gbase 8s creates and uses SPL?
promise 基础使用
Google 为造芯再掀“抢人大战”,英特尔 17 年老将加入!
轻松与劳氏Lowe’s 对接 EDI 要准备什么?
Wallys/3 × 3/2 × 2 MIMO/ 802.11ac/ Mini PCIe /2,4GHz / 5GHz QCA 9880
体系对于哲学的重要性-黑格尔