Deal all,
I want to return multilevel data json to user. something like this
{ "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"
},
]
}
I guess using XML will be more suitable way to represent the data structure, because the screen item and key subitem will be inserted dynamically. Am I correct, or there exist other better way? If using XML, can u shed some light on it?
Thanks
The code below does what you want. The key is to separate the JSON message blocks into logical structs, and then group them together to make the message. See http://blog.golang.org/json-and-go and http://golang.org/pkg/encoding/json/ for more info.
To convert the object to JSON, use the json.Marshal function
.
To convert the object to XML, use the xml.Marshal function
.
The code below uses the MarshalIndent
functions to pretty-print the output.
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
", jsonMsg)
xmlMsg, err := xml.MarshalIndent(msg, "", "\t")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s
", xmlMsg)
}
Will produce:
{
"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>