目录
问题内容
解决方法
首页 后端开发 Golang 如何最好地将 JSON 数据规范化为 Go 中的 API 结构体

如何最好地将 JSON 数据规范化为 Go 中的 API 结构体

Feb 13, 2024 pm 06:06 PM
go语言

如何最好地将 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中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
3 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

Go语言中用于浮点数运算的库有哪些? Go语言中用于浮点数运算的库有哪些? Apr 02, 2025 pm 02:06 PM

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

Go的爬虫Colly中Queue线程的问题是什么? Go的爬虫Colly中Queue线程的问题是什么? Apr 02, 2025 pm 02:09 PM

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

Go语言中哪些库是由大公司开发或知名的开源项目提供的? Go语言中哪些库是由大公司开发或知名的开源项目提供的? Apr 02, 2025 pm 04:12 PM

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

Go语言中`var`和`type`关键字定义结构体的区别是什么? Go语言中`var`和`type`关键字定义结构体的区别是什么? Apr 02, 2025 pm 12:57 PM

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

在Go语言中使用Redis Stream实现消息队列时,如何解决user_id类型转换问题? 在Go语言中使用Redis Stream实现消息队列时,如何解决user_id类型转换问题? Apr 02, 2025 pm 04:54 PM

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

在 Go 语言中,为什么使用 Println 和 string() 函数打印字符串会出现不同的效果? 在 Go 语言中,为什么使用 Println 和 string() 函数打印字符串会出现不同的效果? Apr 02, 2025 pm 02:03 PM

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

在使用Go语言和viper库时,为什么传递指针的指针是必要的? 在使用Go语言和viper库时,为什么传递指针的指针是必要的? Apr 02, 2025 pm 04:00 PM

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

为什么Go语言中使用for range遍历slice并存入map时,所有值会变成最后一个元素? 为什么Go语言中使用for range遍历slice并存入map时,所有值会变成最后一个元素? Apr 02, 2025 pm 04:09 PM

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

See all articles