dtxob80644 2015-12-02 09:58
浏览 103
已采纳

golang在多播ip上发送json

I'm writting a piece of Go to send json data on multicast udp:

func send(a string, messages chan interface{}) {
    addr, err := net.ResolveUDPAddr("udp", a)
    CheckError(err)
    c, err := net.DialUDP("udp", nil, addr)
    CheckError(err)
    for {
        msg := <-messages
        myjson, err := json.Marshal(msg)
        if err != nil {
            fmt.Println("Error encoding JSON")
        return
        }
        //Write to bytes to multicast UDP
        c.Write([]byte(myjson))

        time.Sleep(2 * time.Second)
    }
}

So my json is converted to an array of byte to make it work. Here is my "receiver" func:

func serveMulticastUDP(a string, messages chan interface{}) {

    addr, err := net.ResolveUDPAddr("udp", a)
    CheckError(err)
    l, err := net.ListenMulticastUDP("udp", nil, addr)
    l.SetReadBuffer(maxDatagramSize)
    for {
        b := make([]byte, maxDatagramSize)
        n, src, err := l.ReadFromUDP(b)
        if err != nil {
            log.Fatal("ReadFromUDP failed:", err)
        }
        s := string(b[:n])//here is my problem, I want s to be map[string]interface before sending in my channel
        messages<-s
        log.Println(s)
        log.Println(src)
        log.Println(n)
        //h(src, n, b)
    }
}

How can convert a array of bytes to map[string]interface (json) ?

  • 写回答

1条回答 默认 最新

  • douluohan3403 2015-12-02 10:11
    关注

    In your code you used json.Marshal() to convert your value to JSON text ([]byte).

    The other direction ([]byte -> value) can be done using json.Unmarshal(). json.Unmarshal() expects a []byte so you don't even have to convert it to string.

    See this example:

    data := []byte(`{"key1":"value1","key2":123}`)
    
    var m map[string]interface{}
    if err := json.Unmarshal(data, &m); err != nil {
        panic(err)
    }
    
    fmt.Printf("%+v", m)
    

    Output (try it on the Go Playground):

    map[key1:value1 key2:123]
    

    Notes:

    The result of marshaling (json.Marshal()) is a value of type []byte so you don't need explicit conversion here:

    c.Write([]byte(myjson))
    

    You can simply write:

    c.Write(myjson)
    

    Also when unmarshaling, make sure you pass b[:n] to json.Unmarshal(), as the rest of the slice contains 0s (which your 2nd error suggests) but they are not part of the json text!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况