当前位置: > > > > golang 中的 json marshal araylist
来源:stackoverflow
2024-04-22 21:18:35
0浏览
收藏
最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《golang 中的 json marshal araylist》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~
问题内容
你好,我又回来问了 抱歉,如果你们认为我缺乏搜索,但已经这样做了几个小时,我仍然不明白为什么
我在 golang 中有一个这样的控制器:
c3 := router.createnewcontrollerinstance("index", "/v4") c3.post("/insertemployee", insertemployee)
并使用postman抛出这个arraylist请求,请求是这样的
[{ "idemployee": "emp4570787", "idbranch": "almst", "idjob": "prg", "name": "mikey ivanyushin", "street": "1 bashford point", "phone": "9745288064", "join_date": "2008-09-18", "status": "fulltime" },{ "idemployee": "emp4570787", "idbranch": "almst", "idjob": "prg", "name": "mikey ivanyushin", "street": "1 bashford point", "phone": "9745288064", "join_date": "2008-09-18", "status": "fulltime" }]
而且我还有 2 个这样的结构
type employeerequest struct { idemployee string `json: "id_employee"` idbranch string `json: "id_branch" ` idjob string `json: "id_job" ` name string `json: "name" ` street string `json: "street" ` phone string `json: "phone" ` joindate string `json: "join_date" ` status string `json: "status" ` enabled int `json: "enabled" ` deleted int `json: "deletedstring"` } type listemployeerequest struct { listemployee []employeerequest `json: "request"` }
出于某种原因,当我尝试运行函数来读取从 postman 发送的 json 时,问题就从这里开始
这是我尝试运行的函数
func insertEmployee(ctx context.Context) { tempReq := services.ListEmployeeRequest{} temp1 := ctx.ReadJSON(&tempReq.ListEmployee) var err error if err = ctx.ReadJSON(temp1); config.FancyHandleError(err) { fmt.Println("err readjson ", err.Error()) } parsing, errParsing := json.Marshal(temp1) fmt.Println("", string(parsing)) fmt.Print("", errParsing) }
问题发生在 if err = ctx.readjson(temp1); 行上config.fancyhandleerror(err) 它告诉我,当我抛出来自 postman 的请求时,我得到了 json 输入的意外结束,我是否在那里做错了什么?或者我输入了错误的验证码?
有人可以告诉我下一步该怎么做才能读取我从邮递员那里抛出的 json 吗?
感谢您的关注和帮助,非常喜欢<3
解决方案
您遇到多个问题:
- 标签名称与 json 输入不匹配,例如
id_employee
与idemployee
。 - 您的标记语法不正确,当您运行
go vet
时显示,应该是json:"id_employee"
-
您不需要另一个
list
结构,如果您使用它,您的 json 应该是{"requests":[...]}
。相反,您可以反序列化切片:var requests []employeerequest if err := json.unmarshal([]byte(j), &requests); err != nil { log.fatal(err) }
您可以在此处查看正在运行的版本:
type EmployeeRequest struct { IDEmployee string `json:"IDEmployee"` IDBranch string `json:"IDBranch"` IDJob string `json:"IDJob"` Name string `json:"name"` Street string `json:"street"` Phone string `json:"phone"` JoinDate string `json:"join_date"` Status string `json:"status"` Enabled int `json:"enabled"` Deleted int `json:"deletedstring"` }
一些 json 标签与字段不匹配。
以上就是《golang 中的 json marshal araylist》的详细内容,更多关于的资料请关注公众号!