英文:
golang sending json on multicast ip
问题
你可以使用json.Unmarshal函数将字节数组转换为map[string]interface{}类型的JSON对象。以下是你可以在代码中使用的示例:
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)
        }
        var data map[string]interface{}
        err = json.Unmarshal(b[:n], &data)
        if err != nil {
            log.Println("Error decoding JSON:", err)
            continue
        }
        messages <- data
        log.Println(data)
        log.Println(src)
        log.Println(n)
        //h(src, n, b)
    }
}
在这个示例中,我们首先定义一个data变量,它将存储解码后的JSON对象。然后,我们使用json.Unmarshal函数将字节数组b[:n]解码为data变量。如果解码过程中出现错误,我们将打印错误信息并继续处理下一个数据包。如果解码成功,我们将data变量发送到messages通道中。
希望这可以帮助到你!如果你有任何其他问题,请随时问我。
英文:
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
得分: 5
在你的代码中,你使用了json.Marshal()将值转换为JSON文本([]byte)。
另一个方向([]byte -> 值)可以使用json.Unmarshal()来完成。json.Unmarshal()期望一个[]byte,所以你甚至不需要将其转换为string。
看看这个例子:
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)
输出结果(在Go Playground上尝试):
map[key1:value1 key2:123]
注意:
编组(json.Marshal())的结果是一个[]byte类型的值,所以你不需要在这里进行显式转换:
c.Write([]byte(myjson))
你可以简单地写成:
c.Write(myjson)
此外,在解组时,请确保将b[:n]传递给json.Unmarshal(),因为切片的其余部分包含了0(你的第二个错误提示),但它们不是JSON文本的一部分!
英文:
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!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论