[英]golang | unmarshalling arbitrary data
題
有沒有一種方法可以將JSON數據編組為零件/部分中的編組?
假設數據的上半部分是一個“代碼”,它將指示下半部分的處理方式,例如根據“代碼”將下半部分編組為特定的結構。
下半部分可能會發送兩種結構...
type Range Struct {
Start int
End int
}
type User struct {
ID int
Pass int
}
偽代碼示例
看起來像這樣...
message := &Message{
Code: 4,
&Range {
Start: 1,
End: 10,
}
}
它可能看起來像這樣...
message := &Message{
Code: 3,
&User {
ID: 1,
Pass: 1234,
}
}
因此,當解組數據時,我可以...
// get code from top half
m := Message{}
err = json.UnMarshallTopHalf(byteArray, &m)
if m.Code == 4 {
// ok, the code was four, lets unmarshall into type Range
r := Range{}
json.UnmarshalBottomHalf(byteArray, &r)
}
我看過JSON&Go ,了解如何封送和拆封定義的結構。 我可以這樣做,但是我無法像上面的示例那樣想出一種獲取任意數據的方法...
type Message struct {
Code int `json:"cc"`
Range *Range `json:"vvv,omitempty"`
User *User `json:"fff,omitempty"`
}
然后給定代碼== x,使用范圍,如果是Y,則使用用戶。
您可以先在json.RawMessage中解組下半部分,例如
package main
import (
"encoding/json"
"fmt"
)
type Message struct {
Code int
Payload json.RawMessage // delay parsing until we know the code
}
type Range struct {
Start int
End int
}
type User struct {
ID int
Pass int
}
func MyUnmarshall(m []byte) {
var message Message
var payload interface{}
json.Unmarshal(m, &message) // delay parsing until we know the color space
switch message.Code {
case 3:
payload = new(User)
case 4:
payload = new(Range)
}
json.Unmarshal(message.Payload, payload) //err check ommited for readability
fmt.Printf("\n%v%+v", message.Code, payload) //do something with data
}
func main() {
json := []byte(`{"Code": 4, "Payload": {"Start": 1, "End": 10}}`)
MyUnmarshall(json)
json = []byte(`{"Code": 3, "Payload": {"ID": 1, "Pass": 1234}}`)
MyUnmarshall(json)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.