dongxian3852 2017-08-26 15:21
浏览 33
已采纳

高朗| 解组任意数据

QUESTION

Is there a way to marshall JSON data in such a way that it can be unmarshalled in parts / sections?

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. I can do this, but I cannot figure out a way for arbitrary data as in the example above ...

  • 写回答

2条回答 默认 最新

  • dongtou8736 2017-08-26 17:00
    关注

    You can unmarshall bottom half in json.RawMessage first, something like

    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("
    %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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来