要将给定的 JSON 字符串中的 ipv4Addresses
属性反序列化为数组,并将其存储到定义的 NfProfile
结构体中,你可以使用 Go 语言的标准库以及一些 JSON 处理库。下面是一个示例代码,演示如何完成这个过程。
示例代码
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:"sNssais" bson:"sNssais" mapstructure:"SNssais"`
PerPlmnSnssaiList []PlmnSnssai `json:"perPlmnSnssaiList,omitempty" yaml:"perPlmnSnssaiList" bson:"perPlmnSnssaiList" mapstructure="PerPlmnSnssaiList"`
NsiList []string `json:"nsiList,omitempty" yaml:",omitempty"`
Fqdn string `json:",omitempty"`
InterPlmnFqdn string `json:",omitempty"`
Ipv4Addresses []string `json:",omitempty"`
Ipv6Addresses []string `json:",omitempty"`
AllowedPlmns *[]PlmnId // Assuming you have a type defined for Plmns
}
func main() {
jsonData := `{"ipv4Addresses":"[\"192.168.1.1\", \"10.0.0.1\"]","nfInstanceId":"NF_INSTANCE_ID_12222","nfStatus":"REGISTERED","nfType":"PCF","plmnList":""}`
var intermediate struct {
Ipv4Addresses string `json:"ipv4Addresses"`
NfProfile NfProfile
}
err := json.Unmarshal([]byte(jsonData), &intermediate)
if err != nil {
fmt.Println("Error unmarshalling JSON:", err)
return
}
var ipv4Array []string
err = json.Unmarshal([]byte(intermediate.Ipv4Addresses), &ipv4Array)
if err != nil {
fmt.Println("Error unmarshalling ipv4 addresses:", err)
return
}
// Assign the parsed IPv4 addresses to the nfProfile structure.
nfProfile := intermediate.NfProfile
nfProfile.Ipv4Addresses = ipv4Array
fmt.Printf("Parsed NfProfile: %+v\n", nfProfile)
}
解释:
- 定义数据结构:首先,我们定义了一个名为
NfProfile
的数据结构,它对应于你的需求。 - JSON 解码:我们首先解码原始 JSON 数据到一个临时结构体,其中包含了字符串形式的 IPv4 地址。
- 二次解码:然后,我们再对这个字符串进行解码,转化为实际的 IPv4 地址数组。
- 赋值:最后,将解析出的地址数组赋值给主结构体中的相应字段。
注意事项:
- 确保导入必要的包,例如
"encoding/json"
和"fmt"
。 - 根据具体情况调整其他未完全展示的类型(如
AllowedPlmns
)。 - 输入的 JSON 字符串需要是有效格式,并且符合你预期的结构。
内容由零声教学AI助手提供,问题来源于学员提问