【发布时间】:2018-08-10 17:58:22
【问题描述】:
最近我正在尝试使用 GoLang 作为 Graphql 服务器来实现 Mutation Request,基本上这是我发送的查询:正如你所看到的,它是一个包含 name 和字符串数组
mutation{
CellTest(cells:[{name:"lero",child:["1","2"]},{name:"lero2",child:["12","22"]}]){
querybody
}
}
在我的 Go 代码中,我有一个类型对象,它将设置发送的值
type Cell struct {
name string `json:"name"`
child []string `json:"child"`
}
还有一个自定义数组,它将是 []Cell
type Cells []*Cell
但是,当 GO 收到请求时,我得到以下信息: 请注意,这是 cellsInterface
的打印[map[child:[1 2] name:lero] map[child:[12 22] name:lero2]]
如何获取每个值并在我的 Array Cells 中分配这些值 像这样:
细胞[0] = {name="first",child={"1","2"}}
细胞[1] = {name="second",child={"hello","good"}}
这是我目前的尝试:
var resolvedCells Cells
cellsInterface := params.Args["cells"].([]interface{})
cellsByte, err := json.Marshal(cellsInterface)
if err != nil {
fmt.Println("marshal the input json", err)
return resolvedCells, err
}
if err := json.Unmarshal(cellsByte, &resolvedCells); err != nil {
fmt.Println("unmarshal the input json to Data.Cells", err)
return resolvedCells, err
}
for cell := range resolvedCells {
fmt.Println(cellsInterface[cell].([]interface{}))
}
但是,这只会将单元格数组拆分为 0 和 1。
【问题讨论】:
-
child不是一个映射,而是一个整数值切片。你可以遍历它们,从你问的问题中不清楚你到底想要什么。 -
好吧,我真正想要的是获取在 Mutation 中发送的每个值并将其保存在 Cell 数组中(最后是 Cell 结构类型)
-
我希望我的评论能更清楚一点@Himanshu
-
我编辑了这个问题,所以现在它会更清楚
-
是的,我们可以这样做,只需在您的问题中打印
cellsInterface和resolvedCells的输出即可。
标签: arrays json go struct graphql