Go转json数组 - Go语言中文社区

Go转json数组


Go转json数组

最近因需要要调用gitlab的API,其中有一个是根据私有token获取Repositories列表 由于返回结果是一个json数组,单纯使用json.Unmarshal没法实现,于是在网上找了一下解决方案,并修改如下:

type JSONObj struct {
	data interface{}
}

//Json Initialize the json configruation
func Json(data string) *JSONObj {
	j := new(JSONObj)
	var f interface{}
	err := json.Unmarshal([]byte(data), &f)
	if err != nil {
		return j
	}
	j.data = f
	return j
}

//GetGitLabModel ...
func (j *JSONObj) GetGitLabModel() []*models.Gitlab {
	modelMap := make([]*models.Gitlab, 0)
	for k, _ := range (j.data).([]interface{}) {
		model := &models.Gitlab{}
		if m, ok := (j.data).([]interface{}); ok {
			v := m[k].(map[string]interface{})
			if h, ok := v["name_with_namespace"]; ok {
				model.Name_with_namespace = h.(string)
			}
			if h, ok := v["http_url_to_repo"]; ok {
				model.Http_url_to_repo = h.(string)
			}
			if h, ok := v["public"]; ok {
				model.Public = h.(bool)
			}
		}
		modelMap = append(modelMap, model)
	}
	return modelMap
}

转载于:https://my.oschina.net/johnhjwsosd/blog/869737

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_34221773/article/details/92574000
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-03-08 14:57:28
  • 阅读 ( 765 )
  • 分类:前端

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢