简体   繁体   English

高朗| 解组任意数据

[英]golang | unmarshalling arbitrary data

QUESTION

Is there a way to marshall JSON data in such a way that it can be unmarshalled in parts / sections? 有没有一种方法可以将JSON数据编组为零件/部分中的编组?

Let's say that the top half of data is a "code" which would signal what to do with the bottom half ... such as unmarshall the bottom half into a specific struct depending on the "code". 假设数据的上半部分是一个“代码”,它将指示下半部分的处理方式,例如根据“代码”将下半部分编组为特定的结构。


There are two structs that may be sent as the bottom half ... 下半部分可能会发送两种结构...

type Range Struct {
    Start int
    End   int

}

type User struct {
    ID    int
    Pass  int
}

PSEUDO CODE EXAMPLE 伪代码示例

It may look like this ... 看起来像这样...

message := &Message{
    Code: 4,
    &Range {
        Start: 1,
        End: 10,
    }
}

Itt may look like this ... 它可能看起来像这样...

message := &Message{
    Code: 3,
    &User {
        ID: 1,
        Pass: 1234,
    }
}

So, when unmarshalling that data I could ... 因此,当解组数据时,我可以...

// 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)
}

I have looked at JSON & Go to learn how to marshall and unmarshall defined structs. 我看过JSON&Go ,了解如何封送和拆封定义的结构。 I can do this, but I cannot figure out a way for arbitrary data as in the example above ... 我可以这样做,但是我无法像上面的示例那样想出一种获取任意数据的方法...

type Message struct  {
    Code int `json:"cc"`
    Range *Range `json:"vvv,omitempty"`
    User *User `json:"fff,omitempty"`
}

then given code == x, use range, if Y, use User. 然后给定代码== x,使用范围,如果是Y,则使用用户。

You can unmarshall bottom half in json.RawMessage first, something like 您可以先在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM