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条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀