http – Marshal and Unmarshal nested json object with Go-ThrowExceptions

Exception or error:

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.

How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *