当然可以。除了直接使用 JSON 解码的方式,你还可以通过自定义类型和方法来处理反序列化过程。以下是另一种实现方式,利用 Go 的结构体标签和自定义 Unmarshal 方法。
示例代码
package main
import (
"encoding/json"
"fmt"
)
type NfType string
type NfStatus string
type PlmnId string
type Snssai string
type PlmnSnssai struct{}
type NfProfile struct {
NfInstanceId string `json:"nfInstanceId" yaml:"nfInstanceId" bson:"nfInstanceId" mapstructure:"NfInstanceId"`
NfType NfType `json:"nfType" yaml:"nfType" bson:"nfType" mapstructure:"NfType"`
NfStatus NfStatus `json:"nfStatus" yaml:"nfStatus" bson:"nfStatus" mapstructure:"NfStatus"`
HeartBeatTimer int32 `json:"heartBeatTimer,omitempty" yaml:"heartBeatTimer" bson:"heartBeatTimer" mapstructure:"HeartBeatTimer"`
PlmnList *[]PlmnId `json:"plmnList,omitempty" yaml:"plmnList" bson:"plmnList" mapstructure:"PlmnList"`
SNssais *[]Snssai `json:"sNssais,omitempty" yaml:",omitempty"`
PerPlmnSnssaiList []PlmnSnssai `json:"perPlmnSnssaiList,omitempty" yaml:",omitempty"`
NsiList []string `json:",omitempty"`
Fqdn string `json:",omitempty"`
InterPlmnFqdn string `json:",omitempty"`
Ipv4Addresses []string // 用于存储 IPv4 地址数组
Ipv6Addresses []string // 用于存储 IPv6 地址数组
}
type CustomNfProfile struct {
NfProfile
Ipv4AddressesRaw string `json:"ipv4Addresses"`
}
// UnmarshalJSON 自定义解组函数,用于解析 CustomNfProfile 中的 Ipv4AddressesRaw 字段。
func (c *CustomNfProfile) UnmarshalJSON(data []byte) error {
type Alias CustomNfProfile
aux := &struct {
*Alias
}{
Alias: (*Alias)(c),
}
if err := json.Unmarshal(data, &aux); err != nil {
return err
}
var ipv4Array []string
err := json.Unmarshal([]byte(aux.Ipv4AddressesRaw), &ipv4Array)
if err != nil {
return err
}
c.Ipv4Addresses = ipv4Array
return nil
}
func main() {
jsonData := `{"ipv4Addresses":"[\"192.168.1.1\", \"10.0.0.1\"]","nfInstanceId":"NF_INSTANCE_ID_12222","nfStatus":"REGISTERED","nfType":"PCF","plmnList":""}`
var nfProfile CustomNfProfile
err := json.Unmarshal([]byte(jsonData), &nfProfile)
if err != nil {
fmt.Println("Error unmarshalling JSON:", err)
return
}
fmt.Printf("Parsed NfProfile: %+v\n", nfProfile)
}
解释:
自定义结构体:我们创建了一个名为
CustomNfProfile
的新结构体,它嵌入了原始的NfProfile
结构体,并添加了一个字段用于接收原始的 IPv4 地址字符串。自定义 Unmarshal 方法:我们为
CustomNfProfile
实现了UnmarshalJSON
方法。在这个方法中,我们首先解析 JSON 数据,然后单独解析被封装在字符串中的 IPv4 地址,将其转换成数组并赋值给主结构体的相应字段。使用时简洁:在使用时,我们只需要解码到自定义结构体实例,这样就能自动完成原始数据的解码和后续处理。
这种方式的好处是将逻辑与数据分离,使得你的代码更加清晰易读,并且方便扩展。
内容由零声教学AI助手提供,问题来源于学员提问