登录
首页 >  Golang >  Go问答

解组对象数组时由于 nil 映射而发生崩溃的 JSON 处理

来源:stackoverflow

时间:2024-02-11 08:54:23 460浏览 收藏

珍惜时间,勤奋学习!今天给大家带来《解组对象数组时由于 nil 映射而发生崩溃的 JSON 处理》,正文内容主要涉及到等等,如果你正在学习Golang,或者是对Golang有疑问,欢迎大家关注我!后面我会持续更新相关内容的,希望都能帮到正在学习的大家!

问题内容

我有以下最小复制,当此代码运行时,它会在 basicmap[key] = value 处抛出异常,因为 分配给 nil map 中的条目,但是仅当类型为 []custommap 时才会执行此操作 - 当我使用时custommap 用于单个项目,它工作得很好。

有没有办法在 go 中解组自定义对象数组?

package main

import "encoding/json"

type CustomMap map[string]any

type Payload struct {
    Items []CustomMap `json:"items"`
}

func mapToBasicMap(basicMap CustomMap, aMap map[string]any) {
    for key, value := range aMap {
        basicMap[key] = value
    }
}

func (this CustomMap) UnmarshalJSON(data []byte) error {
    var aMap map[string]any = make(map[string]any)
    json.Unmarshal(data, &aMap)
    mapToBasicMap(this, aMap)
    return nil
}
func main() {
    payload := Payload{}
    json.Unmarshal([]byte("{\"items\":[{\"item1\": 1}]}"), &payload)
}

正确答案


unmarshal 应该有一个指针接收器。在使用分配值之前先创建目标映射。

func (this *CustomMap) UnmarshalJSON(data []byte) error {
    var aMap map[string]any = make(map[string]any)
    json.Unmarshal(data, &aMap)
    *this = make(CustomMap)
    mapToBasicMap(*this, aMap)
    return nil
}

另一个修复方法是删除方法 custommap.unmarshaljson

今天关于《解组对象数组时由于 nil 映射而发生崩溃的 JSON 处理》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>