gpt4 book ai didi

xml - Go多级数据结构

转载 作者:数据小太阳 更新时间:2023-10-29 03:35:56 26 4
gpt4 key购买 nike

全部处理,

我想返回多级数据 json 给用户。像这样

{ "screen"[{ 
"screen_id":"001",
"screen_name":"screen_001"
"key": [ {
"id":"key_001",
"name":"key_001"
},
{
"id":"key_002",
"name":"key_002"
},
]
},
"screen_id":"002",
"screen_name":"screen_002"
"key": [ {
"id":"key_002",
"name":"key_002"
},
{
"id":"key_003",
"name":"key_003"
},
]
}

我想使用 XML 将更适合表示数据结构的方式,因为屏幕项目和关键子项目将被动态插入。我是对的,还是存在其他更好的方法?如果使用 XML,您能否说明一下?

谢谢

最佳答案

下面的代码可以满足您的需求。关键是将 JSON 消息 block 分离成逻辑结构,然后将它们组合在一起以构成消息。参见 http://blog.golang.org/json-and-gohttp://golang.org/pkg/encoding/json/了解更多信息。

要将对象转换为 JSON,请使用 json.Marshal function .

要将对象转换为 XML,请使用 xml.Marshal function .

下面的代码使用 MarshalIndent 函数来漂亮地打印输出。

package main

import (
"encoding/json"
"encoding/xml"
"fmt"
"log"
)

type Key struct {
Id string `json:"id" xml:"id"`
Name string `json:"name" xml:"name"`
}

type Screen struct {
ScreenId string `json:"screen_id" xml:"screen_id"`
ScreenName string `json:"screen_name" xml:"screen_name"`
Keys []Key `json:"key" xml:"key"`
}

type Message struct {
Screens []Screen `json:"screen" xml:"screen"`
}

func main() {

msg := Message{
[]Screen{
Screen{
"001",
"screen_001",
[]Key{
Key{
"key_001",
"key_001",
},
Key{
"key_002",
"key_002",
},
},
},
Screen{
"002",
"screen_002",
[]Key{
Key{
"key_002",
"key_002",
},
Key{
"key_003",
"key_003",
},
},
},
},
}

jsonMsg, err := json.MarshalIndent(msg, "", "\t")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s\n", jsonMsg)

xmlMsg, err := xml.MarshalIndent(msg, "", "\t")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s\n", xmlMsg)
}

将产生:

{
"screen": [
{
"screen_id": "001",
"screen_name": "screen_001",
"key": [
{
"id": "key_001",
"name": "key_001"
},
{
"id": "key_002",
"name": "key_002"
}
]
},
{
"screen_id": "002",
"screen_name": "screen_002",
"key": [
{
"id": "key_002",
"name": "key_002"
},
{
"id": "key_003",
"name": "key_003"
}
]
}
]
}
<Message>
<screen>
<screen_id>001</screen_id>
<screen_name>screen_001</screen_name>
<key>
<id>key_001</id>
<name>key_001</name>
</key>
<key>
<id>key_002</id>
<name>key_002</name>
</key>
</screen>
<screen>
<screen_id>002</screen_id>
<screen_name>screen_002</screen_name>
<key>
<id>key_002</id>
<name>key_002</name>
</key>
<key>
<id>key_003</id>
<name>key_003</name>
</key>
</screen>
</Message>

Playground

关于xml - Go多级数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25256219/

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