ZBLOG

还有别的实现吗

当然可以。除了直接使用 JSON 解码的方式,你还可以通过自定义类型和方法来处理反序列化过程。以下是另一种实现方式,利用 Go 的结构体标签和自定义 Unmarshal 方法。

示例代码

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. )
  6. type NfType string
  7. type NfStatus string
  8. type PlmnId string
  9. type Snssai string
  10. type PlmnSnssai struct{}
  11. type NfProfile struct {
  12. NfInstanceId string `json:"nfInstanceId" yaml:"nfInstanceId" bson:"nfInstanceId" mapstructure:"NfInstanceId"`
  13. NfType NfType `json:"nfType" yaml:"nfType" bson:"nfType" mapstructure:"NfType"`
  14. NfStatus NfStatus `json:"nfStatus" yaml:"nfStatus" bson:"nfStatus" mapstructure:"NfStatus"`
  15. HeartBeatTimer int32 `json:"heartBeatTimer,omitempty" yaml:"heartBeatTimer" bson:"heartBeatTimer" mapstructure:"HeartBeatTimer"`
  16. PlmnList *[]PlmnId `json:"plmnList,omitempty" yaml:"plmnList" bson:"plmnList" mapstructure:"PlmnList"`
  17. SNssais *[]Snssai `json:"sNssais,omitempty" yaml:",omitempty"`
  18. PerPlmnSnssaiList []PlmnSnssai `json:"perPlmnSnssaiList,omitempty" yaml:",omitempty"`
  19. NsiList []string `json:",omitempty"`
  20. Fqdn string `json:",omitempty"`
  21. InterPlmnFqdn string `json:",omitempty"`
  22. Ipv4Addresses []string // 用于存储 IPv4 地址数组
  23. Ipv6Addresses []string // 用于存储 IPv6 地址数组
  24. }
  25. type CustomNfProfile struct {
  26. NfProfile
  27. Ipv4AddressesRaw string `json:"ipv4Addresses"`
  28. }
  29. // UnmarshalJSON 自定义解组函数,用于解析 CustomNfProfile 中的 Ipv4AddressesRaw 字段。
  30. func (c *CustomNfProfile) UnmarshalJSON(data []byte) error {
  31. type Alias CustomNfProfile
  32. aux := &struct {
  33. *Alias
  34. }{
  35. Alias: (*Alias)(c),
  36. }
  37. if err := json.Unmarshal(data, &aux); err != nil {
  38. return err
  39. }
  40. var ipv4Array []string
  41. err := json.Unmarshal([]byte(aux.Ipv4AddressesRaw), &ipv4Array)
  42. if err != nil {
  43. return err
  44. }
  45. c.Ipv4Addresses = ipv4Array
  46. return nil
  47. }
  48. func main() {
  49. jsonData := `{"ipv4Addresses":"[\"192.168.1.1\", \"10.0.0.1\"]","nfInstanceId":"NF_INSTANCE_ID_12222","nfStatus":"REGISTERED","nfType":"PCF","plmnList":""}`
  50. var nfProfile CustomNfProfile
  51. err := json.Unmarshal([]byte(jsonData), &nfProfile)
  52. if err != nil {
  53. fmt.Println("Error unmarshalling JSON:", err)
  54. return
  55. }
  56. fmt.Printf("Parsed NfProfile: %+v\n", nfProfile)
  57. }

解释:

  1. 自定义结构体:我们创建了一个名为CustomNfProfile的新结构体,它嵌入了原始的NfProfile结构体,并添加了一个字段用于接收原始的 IPv4 地址字符串。

  2. 自定义 Unmarshal 方法:我们为CustomNfProfile实现了UnmarshalJSON方法。在这个方法中,我们首先解析 JSON 数据,然后单独解析被封装在字符串中的 IPv4 地址,将其转换成数组并赋值给主结构体的相应字段。

  3. 使用时简洁:在使用时,我们只需要解码到自定义结构体实例,这样就能自动完成原始数据的解码和后续处理。

这种方式的好处是将逻辑与数据分离,使得你的代码更加清晰易读,并且方便扩展。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:http://sdn.0voice.com/?id=7133

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?