Golang graphql 使用子映射迭代地图



>最近我尝试使用 GoLang 作为 Graphql 服务器实现突变请求,基本上这是我发送的查询: 如您所见,它是一个包含名称和字符串

数组的对象数组
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收到请求时,我得到这个: 注意这是单元格接口的打印

[地图[儿童:[1 2] 姓名:莱罗]

地图[儿童:[12 22] 姓名:莱罗2]]

如何获取每个值并在我的数组单元格中分配如下所示的值:

单元格[0] = {名称="第一个",子项={"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。

范围浏览结果中的映射值,并将这些值附加到单元格切片。如果您从 json 获取对象。然后,您可以将字节解组到单元格中。

解组时的结果应该是 Cell 结构的一部分,如下所示

var resolvedCells []Cell
if err := json.Unmarshal(cellsByte, &resolvedCells); err != nil {
fmt.Println("unmarshal the input json to Data.Cells", err)
}
fmt.Println(resolvedCells)

围棋操场上的工作代码

或者,如果您想在解析的单元格上使用指针循环作为

type Cells []*Cell
func main() {
var resolvedCells Cells
if err := json.Unmarshal(cellsByte, &resolvedCells); err != nil {
fmt.Println("unmarshal the input json to Data.Cells", err)
}
fmt.Println(*resolvedCells[1])
for _, value := range resolvedCells{
fmt.Println(value)
fmt.Printf("%+v",value.Child) // access child struct value of array
}
}

游乐场示例

最新更新