gpt4 book ai didi

json - Golang 中的动态 JSON 结构未按预期运行

转载 作者:IT王子 更新时间:2023-10-29 02:37:02 28 4
gpt4 key购买 nike

我正在尝试创建一个结构,其中包含一些始终存在的基本字段和一些本身就是结构的可选字段。

我想知道为什么下面的代码:

package main

import (
"encoding/json"
"fmt"
"time"
)

type DataManagement struct {
DataManagement struct {
Type string
Asset struct {
LocalAssetUID string
Type string
}
*ContentProductionOrder
*ContentItem
TimeStamp time.Time
Hash string
}
}

type ContentProductionOrder struct {
ProductionOrderNo int
ItemNo int
StartDate time.Time
FinishDate time.Time
StatusID int
StatusDate time.Time
SourceTypeID int
TrackingID int
}

type ContentItem struct {
ItemNo int
ItemText string
Quantity int
}

func main() {
var contentItem ContentItem
contentItem.ItemNo = 123
contentItem.ItemText = "aaaaaaaa"
contentItem.Quantity = 3

var dataManagement DataManagement
dataManagement.DataManagement.Type = "asd"
dataManagement.DataManagement.Asset.LocalAssetUID = "asd"
dataManagement.DataManagement.Asset.Type = "asd"
dataManagement.DataManagement.ContentItem = &contentItem
dataManagement.DataManagement.TimeStamp = time.Now().UTC()
dataManagement.DataManagement.Hash = "123"

xy, _ := json.MarshalIndent(dataManagement, "", " ")
fmt.Println(string(xy))
xy, _ = json.MarshalIndent(contentItem, "", " ")
fmt.Println(string(xy))
}

输出到以下内容:

{
"DataManagement": {
"Type": "asd",
"Asset": {
"LocalAssetUID": "asd",
"Type": "asd"
},
"ItemText": "aaaaaaaa",
"Quantity": 3,
"TimeStamp": "2009-11-10T23:00:00Z",
"Hash": "123"
}
}
{
"ItemNo": 123,
"ItemText": "aaaaaaaa",
"Quantity": 3
}

而不是:

{
"DataManagement": {
"Type": "asd",
"Asset": {
"LocalAssetUID": "asd",
"Type": "asd"
},
"ContentItem": {
"ItemNo": 123,
"ItemText": "aaaaaaaa",
"Quantity": 3
},
"TimeStamp": "2009-11-10T23:00:00Z",
"Hash": "123"
}
}
{
"ItemNo": 123,
"ItemText": "aaaaaaaa",
"Quantity": 3
}

有什么想法吗?这可能很容易解释;我在 Golang 方面经验不足。

这是一个 Playground 链接:https://play.golang.org/p/iRDcaRIZ_ZU

最佳答案

您没有得到想要的输出是因为您在 DataManagement 中为 ContentItem 使用了嵌入式结构,而不是将字段名称添加到结构中。

A field declared with a type but no explicit field name is called an embedded field. An embedded field must be specified as a type name T or as a pointer to a non-interface type name *T, and T itself may not be a pointer type. The unqualified type name acts as the field name.

字段声明将解决您的问题。您应该将结构 DataManagement 更改为:

type DataManagement struct {
DataManagement struct {
Type string
Asset struct {
LocalAssetUID string
Type string
}
*ContentProductionOrder // this is embedded struct
ContentItem *ContentItem
TimeStamp time.Time
Hash string
}
}

关于 Go Playground 的工作代码

有关更多信息,请查看 Struct Types 的 Golang 规范

关于json - Golang 中的动态 JSON 结构未按预期运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51968946/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com