普通网友 2019-09-07 19:56
浏览 177

使用Go进行元帅和Unmarshal嵌套json对象

I'm developing a little application using Go. I have a little problem. My application uses "objects" (structs) like this:

type Message1 struct {
   Id string `json:"id"`
   N int `json:"n"`
}

This application sends these objects using HTTP to other processes, using the json format. I do the following thing like this (an example):

methodSend() {
    jsonData := Message1{
        Id: "my_id"
        N: 3 }
    jsonValue, _ := json.Marshal(jsonData)
    _, err := http.Post("http://address", "application/json", bytes.NewBuffer(jsonValue))
    // error management...
}

methodReceive(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    var my_message Message1
    _ = json.NewDecoder(r.Body).Decode(&my_message)
}

If, for example, I create this thing:

type Nested struct {
    id string
    num int
}

type Message2 struct {
   Id string `json:"id"`
   N Nested `json:"n"`
}

And if I use the same approach as before (obviously using a reference to a Nested object rather than a numeric value) the application does'nt work and the parameter passed as "object" when received is not properly containing the data as it should. I'm sure that it's a "nesting" problem of complex objects, but I have no idea what is the best way to do it without spoiling the created structs and the logic of the program.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥20 求一个html代码,有偿
    • ¥100 关于使用MATLAB中copularnd函数的问题
    • ¥20 在虚拟机的pycharm上
    • ¥15 jupyterthemes 设置完毕后没有效果
    • ¥15 matlab图像高斯低通滤波
    • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
    • ¥15 钢筋实图交点识别,机器视觉代码
    • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
    • ¥50 400g qsfp 光模块iphy方案
    • ¥15 两块ADC0804用proteus仿真时,出现异常