Golang中嵌套JSON解析问题求助

Golang中嵌套JSON解析问题求助 我正在解析嵌套的JSON数据,但遇到了一个奇怪的结果。在打印语句中,我能获取到产品描述,但无法获取产品名称和位置信息。如有任何帮助,将不胜感激。

tempDevs := myDevs.DevInstances
	for _, dev := range tempDevs {
		fmt.Printf("serialNumber = %s\n",dev.SerialNumber)
		fmt.Printf("ProductName = %s\n",dev.Product.PName)
		fmt.Printf("ProductNumber = %s\n",dev.Product.PNumber)
		fmt.Printf("ProductDescription = %s\n",dev.Product.PDescription)
		fmt.Printf("Location = %s\n",dev.Product.PLocation)
		fmt.Printf("\n")
	}

以下是数据格式示例: ‘’’{“totalRecords”:2,“instances”:[{“serialNumber”:“testSN1”,“parentSerialNumber”:“anotherSN”,“minor”:false,“instanceNumber”:“8765345678”,“installedBaseStatus”:“Latest-INSTALLED”,“endCustomer”:{“id”:“1”,“name”:“test client”,“address”:{“address1”:“100 myStreet”,“city”:“Albany”,“country”:“US”,“state”:“NY”,“postalCode”:“12345”}},“serviceSKU”:“testSKU1”,“serviceLevel”:“SL1”,“serviceDescription”:“testdesc1”,“startDate”:“2018-04-09T00:00:00Z”,“endDate”:“2019-04-08T00:00:00Z”,“product”:{“number”:“productNumber1”,“description”:“test product desc”,“family”:“fam1”,“group”:“group1”,“location”:“80616”,“name”:“test product name”},

以下是我构建的结构体: ‘’’ type DeviceInstances struct { SerialNumber string json:"serialNumber" ParentSerialNumber string json:"parentSerialNumber" Minor bool json:"minor" InstanceNumber string json:"instanceNumber" InstalledBaseStatus string json:"installedBaseStatus" ServiceSKU string json:"serviceSKU" ServiceLevel string json:"serviceLevel" ServiceDescription string json:"serviceDescription" StartDate string json:"startDate" EndDate string json:"endDate" MacId string json:"macId" CartonId string json:"cartonId" Quantity int json:"quantity" SalesOrderNumber string json:"salesOrderNumber" PurchaseOrderNumber string json:"purchaseOrderNumber" MaintenanceSalesOrderNumber string json:"maintenanceSalesOrderNumber" MaintenancePurchaseOrderNumber string json:"maintenancePurchaseOrderNumber" ItemType string json:"itemType" ShipDate string json:"shipDate" Product DeviceProduct json:"product" }

type DeviceProduct struct { PName string json:"name" PNumber string json:"number" PDescription string json:"description" PLocation string json:"location" } ‘’’


更多关于Golang中嵌套JSON解析问题求助的实战教程也可以访问 https://www.itying.com/category-94-b0.html

4 回复

你的代码看起来没问题。但你提供的 JSON 不正确,末尾缺少了 }]},不过这应该不是错误原因,因为在 Go 中解码这样的 JSON 会报错。如果你打印整个结构体:

fmt.Printf("%#v\n", dev)

还有其他字段缺失吗?

更多关于Golang中嵌套JSON解析问题求助的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


嗨,约翰,

是的,我之前没见过那个工具,真是太棒了!这是用户操作错误。实际数据要大得多,当我在构建结构体时读取数据时,我把发货地址的字段直接添加到了产品段落中。我使用了你提供的工具并调整了我的代码,现在它工作正常。感谢你的帮助!

谢谢,

凯文

你好

我使用了 https://mholt.github.io/json-to-go/ 根据你的 JSON 生成了这个结构体

{"totalRecords":2,"instances":[{"serialNumber":"testSN1","parentSerialNumber":"anotherSN","minor":false,"instanceNumber":"8765345678","installedBaseStatus":"Latest-INSTALLED","endCustomer":{"id":"1","name":"test client","address":{"address1":"100 myStreet","city":"Albany","country":"US","state":"NY","postalCode":"12345"}},"serviceSKU":"testSKU1","serviceLevel":"SL1","serviceDescription":"testdesc1","startDate":"2018-04-09T00:00:00Z","endDate":"2019-04-08T00:00:00Z","product":{"number":"productNumber1","description":"test product desc","family":"fam1","group":"group1","location":"80616","name":"test product name"}}]}
type AutoGenerated struct {
	TotalRecords int `json:"totalRecords"`
	Instances    []struct {
		SerialNumber        string `json:"serialNumber"`
		ParentSerialNumber  string `json:"parentSerialNumber"`
		Minor               bool   `json:"minor"`
		InstanceNumber      string `json:"instanceNumber"`
		InstalledBaseStatus string `json:"installedBaseStatus"`
		EndCustomer         struct {
			ID      string `json:"id"`
			Name    string `json:"name"`
			Address struct {
				Address1   string `json:"address1"`
				City       string `json:"city"`
				Country    string `json:"country"`
				State      string `json:"state"`
				PostalCode string `json:"postalCode"`
			} `json:"address"`
		} `json:"endCustomer"`
		ServiceSKU         string    `json:"serviceSKU"`
		ServiceLevel       string    `json:"serviceLevel"`
		ServiceDescription string    `json:"serviceDescription"`
		StartDate          time.Time `json:"startDate"`
		EndDate            time.Time `json:"endDate"`
		Product            struct {
			Number      string `json:"number"`
			Description string `json:"description"`
			Family      string `json:"family"`
			Group       string `json:"group"`
			Location    string `json:"location"`
			Name        string `json:"name"`
		} `json:"product"`
	} `json:"instances"`
}

问题出现在结构体字段标签与JSON键的映射不匹配上。在您的JSON数据中,产品字段使用的是"name""number""description""location",但您的结构体字段标签中使用了PNamePNumberPDescriptionPLocation作为标签值,这导致JSON解析时无法正确映射。

以下是修正后的结构体定义:

type DeviceProduct struct {
    PName        string `json:"name"`
    PNumber      string `json:"number"`
    PDescription string `json:"description"`
    PLocation    string `json:"location"`
}

但根据您的描述,问题可能在于JSON数据中的嵌套结构。请确保您的根结构体也正确映射。以下是完整的示例代码:

type DeviceInstancesResponse struct {
    TotalRecords int              `json:"totalRecords"`
    Instances    []DeviceInstances `json:"instances"`
}

type DeviceInstances struct {
    SerialNumber    string        `json:"serialNumber"`
    ParentSerialNumber string     `json:"parentSerialNumber"`
    Minor           bool          `json:"minor"`
    InstanceNumber  string        `json:"instanceNumber"`
    InstalledBaseStatus string    `json:"installedBaseStatus"`
    ServiceSKU      string        `json:"serviceSKU"`
    ServiceLevel    string        `json:"serviceLevel"`
    ServiceDescription string     `json:"serviceDescription"`
    StartDate       string        `json:"startDate"`
    EndDate         string        `json:"endDate"`
    Product         DeviceProduct `json:"product"`
}

type DeviceProduct struct {
    PName        string `json:"name"`
    PNumber      string `json:"number"`
    PDescription string `json:"description"`
    PLocation    string `json:"location"`
}

// 解析示例
func main() {
    var response DeviceInstancesResponse
    err := json.Unmarshal([]byte(jsonData), &response)
    if err != nil {
        log.Fatal(err)
    }

    for _, dev := range response.Instances {
        fmt.Printf("serialNumber = %s\n", dev.SerialNumber)
        fmt.Printf("ProductName = %s\n", dev.Product.PName)
        fmt.Printf("ProductNumber = %s\n", dev.Product.PNumber)
        fmt.Printf("ProductDescription = %s\n", dev.Product.PDescription)
        fmt.Printf("Location = %s\n", dev.Product.PLocation)
        fmt.Printf("\n")
    }
}

如果问题仍然存在,请检查您的JSON数据是否完整,特别是产品字段中的namelocation键是否存在且拼写正确。

回到顶部