在你的数据中,有一些字段的格式不符合预期。例如,ipv4Addresses
字段是一个字符串,而应该是一个字符串数组(slice)。此外,plmnList
目前为空字符串,这可能需要调整为适当的结构。
下面是你给出的 JSON 数据的修改建议和相应解析代码。
修改后的 JSON 数据
根据你的 NfProfile
结构体定义,正确的 JSON 应该类似于:
{
"ipv4Addresses": ["192.168.1.1", "10.0.0.1"],
"nfInstanceId": "NF_INSTANCE_ID_12222",
"nfStatus": "REGISTERED",
"nfType": "PCF",
"plmnList": []
}
修改后解析代码示例
以下是如何从修正后的 JSON 数据解析到 Go 的 NfProfile
结构体:
package main
import (
"encoding/json"
"fmt"
)
type NfType string
type NfStatus string
type PlmnId struct {
ID string `json:"ID"`
}
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"`
Ipv4Addresses []string `json:"ipv4Addresses,omitempty"`
PlmnList []PlmnId `json:"plmnList,omitempty"` // 改为切片以匹配结构体定义
}
func main() {
jsonData := `
{
"ipv4Addresses": ["192.168.1.1", "10.0.0.1"],
"nfInstanceId": "NF_INSTANCE_ID_12222",
"nfStatus": "REGISTERED",
"nfType": "PCF",
"plmnList": []
}`
var profile NfProfile
err := json.Unmarshal([]byte(jsonData), &profile)
if err != nil {
fmt.Println("Error unmarshalling JSON:", err)
return
}
fmt.Printf("Parsed NfProfile: %+v\n", profile)
}
注意事项
- 确保字段类型匹配:在结构体中的字段类型要与传入 JSON 中对应字段的数据类型一致。例如,
ipv4Addresses
必须是一个字符串切片。 - 空数组处理:如果某个字段如
plmnList
没有值,应使用空数组表示,而不是空字符串。
通过以上步骤,你可以成功地将修正后的 JSON 数据解析到 Go 的结构体中。
内容由零声教学AI助手提供,问题来源于学员提问