MST

星途 面试题库

面试题:Go语言struct标签与JSON反序列化的复杂场景处理

假设有如下结构体定义:`type Order struct { OrderID string `, ` Items []Item `, ` TotalPrice float64 `} type Item struct { ItemID string `, ` Quantity int `, ` Price float64 `}`,现要将一段JSON字符串`{"OrderID":"12345","Items":[{"ItemID":"item1","Quantity":2,"Price":10.5},{"ItemID":"item2","Quantity":1,"Price":5.0}],"TotalPrice":26.0}`反序列化为`Order`结构体实例。但JSON中的`ItemID`在Go结构体中应映射为`ProductID`,请写出完整代码实现反序列化并阐述如何通过struct标签解决字段名不一致问题。
33.9万 热度难度
编程语言Go

知识考点

AI 面试

面试题答案

一键面试
package main

import (
    "encoding/json"
    "fmt"
)

type Order struct {
    OrderID    string `json:"OrderID"`
    Items      []Item `json:"Items"`
    TotalPrice float64 `json:"TotalPrice"`
}

type Item struct {
    ProductID string  `json:"ItemID"`
    Quantity  int     `json:"Quantity"`
    Price     float64 `json:"Price"`
}

func main() {
    jsonStr := `{"OrderID":"12345","Items":[{"ItemID":"item1","Quantity":2,"Price":10.5},{"ItemID":"item2","Quantity":1,"Price":5.0}],"TotalPrice":26.0}`
    var order Order
    err := json.Unmarshal([]byte(jsonStr), &order)
    if err != nil {
        fmt.Println("反序列化错误:", err)
        return
    }
    fmt.Printf("反序列化结果: %+v\n", order)
}

通过struct标签解决字段名不一致问题阐述

在Go语言中,通过在结构体字段定义后使用反引号包裹的标签(tag)来解决JSON字段名和结构体字段名不一致的问题。在上述代码中,ProductID 结构体字段定义后的 json:"ItemID" 标签表明,在反序列化时,JSON中的ItemID字段应该映射到Go结构体中的ProductID字段。同样,Order 结构体中的各个字段也通过类似的标签指定了与JSON中字段的对应关系。这样,json.Unmarshal函数在反序列化时就会按照这些标签进行正确的映射。