如何最好地将 JSON 数据规范化为 Go 中的 API 结构体
php小编西瓜在这里带来了一篇关于如何将JSON数据规范化为Go中的API结构体的精简指南。在现代Web应用程序中,与JSON数据打交道是常见的任务。Go语言作为一门强大的后端语言,提供了一种简洁而灵活的方式来处理JSON数据。本文将介绍如何使用Go语言中的结构体来规范化JSON数据,从而更好地处理和操作它们。无论你是初学者还是有经验的开发人员,本文都将为你提供有用的技巧和实用的示例。让我们开始吧!
问题内容
我对 go 还很陌生,正在尝试确定是否有更简洁的方法来完成从前端 (js) 到我的 api 的 json 数据的规范化。为了确保在从结构 (model.expense) 创建变量时使用正确的类型,我将有效负载转储到映射中,然后规范化并保存回结构。如果有人可以教我更好的方法来处理这个问题,我将不胜感激!提前致谢!
模型.费用结构:
type expense struct { id primitive.objectid `json:"_id,omitempty" bson:"_id,omitempty"` name string `json:"name"` frequency int `json:"frequency"` startdate *time.time `json:"startdate"` enddate *time.time `json:"enddate,omitempty"` cost primitive.decimal128 `json:"cost"` paid []string `json:"paid,omitempty"` }
有问题的控制器:
func InsertOneExpense(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.Header().Set("Allow-Control-Allow-Methods", "POST") var expense map[string]interface{} json.NewDecoder(r.Body).Decode(&expense) var expenseName string if name, ok := expense["name"]; ok { expenseName = fmt.Sprintf("%v", name) } else { json.NewEncoder(w).Encode("missing required name") } var expenseFrequency int if frequency, ok := expense["frequency"]; ok { expenseFrequency = int(frequency.(float64)) } else { expenseFrequency = 1 } // Handle startDate normalization var expenseStartDate *time.Time if startDate, ok := expense["startDate"]; ok { startDateString := fmt.Sprintf("%v", startDate) startDateParsed, err := time.Parse("2006-01-02 15:04:05", startDateString) if err != nil { log.Fatal(err) } expenseStartDate = &startDateParsed } else { json.NewEncoder(w).Encode("missing required startDate") } // Handle endDate normalization var expenseEndDate *time.Time if endDate, ok := expense["endDate"]; ok { endDateString := fmt.Sprintf("%v", endDate) endDateParsed, err := time.Parse("2006-01-02 15:04:05", endDateString) if err != nil { log.Fatal(err) } expenseEndDate = &endDateParsed } else { expenseEndDate = nil } // Handle cost normaliztion var expenseCost primitive.Decimal128 if cost, ok := expense["cost"]; ok { costString := fmt.Sprintf("%v", cost) costPrimitive, err := primitive.ParseDecimal128(costString) if err != nil { log.Fatal(err) } expenseCost = costPrimitive } else { json.NewEncoder(w).Encode("missing required cost") return } normalizedExpense := model.Expense{ Name: expenseName, Frequency: expenseFrequency, StartDate: expenseStartDate, EndDate: expenseEndDate, Cost: expenseCost, } // Do more things with the struct var... }
解决方法
您可以定义 json.unmarshaljson
接口,然后根据需要手动验证数据。尝试这样的事情:
package main import ( "encoding/json" "fmt" "strconv" ) type CoolStruct struct { MoneyOwed string `json:"money_owed"` } // UnmarshalJSON the json package will delegate deserialization to our code if we implement the json.UnmarshalJSON interface func (c *CoolStruct) UnmarshalJSON(data []byte) error { // get the body as a map[string]*[]byte raw := map[string]*json.RawMessage{} if err := json.Unmarshal(data, &raw); err != nil { return fmt.Errorf("unable to unmarshal raw meessage map: %w", err) } // if we don't know the variable type sent we can unmarshal to an interface var tempHolder interface{} err := json.Unmarshal(*raw["money_owed"], &tempHolder) if err != nil { return fmt.Errorf("unable to unmarshal custom value from raw message map: %w", err) } // the unmarshalled interface has an underlying type use go's typing // system to determine type conversions / normalizations required switch tempHolder.(type) { case int64: // once we determine the type of the we just assign the value // to the receiver's field c.MoneyOwed = strconv.FormatInt(tempHolder.(int64), 10) // we could list all individually or as a group; driven by requirements case int, int32, float32, float64: c.MoneyOwed = fmt.Sprint(tempHolder) case string: c.MoneyOwed = tempHolder.(string) default: fmt.Printf("missing type case: %T\n", tempHolder) } // success; struct is now populated return nil } func main() { myJson := []byte(`{"money_owed": 123.12}`) cool := CoolStruct{} // outside of your struct you marshal/unmarshal as normal if err := json.Unmarshal(myJson, &cool); err != nil { panic(err) } fmt.Printf("%+v\n", cool) }
输出:{moneyowed:123.12}
游乐场链接:https://www.php.cn/link/87ca4eb840b6f78e3b6d6b418c0fef40
以上是如何最好地将 JSON 数据规范化为 Go 中的 API 结构体的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

热门话题

Go语言中用于浮点数运算的库介绍在Go语言(也称为Golang)中,进行浮点数的加减乘除运算时,如何确保精度是�...

Go爬虫Colly中的Queue线程问题探讨在使用Go语言的Colly爬虫库时,开发者常常会遇到关于线程和请求队列的问题。�...

Go语言中哪些库是大公司开发或知名开源项目?在使用Go语言进行编程时,开发者常常会遇到一些常见的需求,�...

Go语言中结构体定义的两种方式:var与type关键字的差异Go语言在定义结构体时,经常会看到两种不同的写法:一�...

Go语言中使用RedisStream实现消息队列时类型转换问题在使用Go语言与Redis...

Go语言中字符串打印的区别:使用Println与string()函数的效果差异在Go...

Go指针语法及viper库使用中的寻址问题在使用Go语言进行编程时,理解指针的语法和使用方法至关重要,尤其是在...

为什么Go语言中的map迭代会导致所有值变成最后一个元素?在Go语言中,面对一些面试题时,经常会遇到关于map�...
