Emixam23
Emixam23

Reputation: 3964

Struct with interface to json

I'm asking myself about an error that I got. I'm making an API which send a response which seems like it:

var StatusBack struct {
    Description string // to describe the error/the result
    StatusId int // the status number (500 Internal error, 200 OK...)
}
// client get 
{
    description: "{surname: \"Xthing\", firstname: \"Mister\"}"
    status_id: 200
}

So my idea was to make a json into a string with Marshal and then, Marshal a second time the StatusBack struct to send it. However, it doesn't make what I really want which is to get an object which contain another object. The client only get one object which contain a string..The thing is, I don't send only user as result, so like I show below I think I need an interface

var StatusBack struct {
    Description string // to describe the error
    Result <Interface or object, I don t know> // which is the result
    StatusId int // the status number (500 Internal error, 200 OK...)
}
// client get 
{
    description: "User information",
    result: {
        surname: "Xthing",
        firstname: "Mister"
    },
    status_id: 200
}

Like I said before, I not only send user, it could be lot of different object, so how can I achieves it? Does my second idea is better? If yes, how can I code it?

Upvotes: 0

Views: 4305

Answers (1)

T. Claverie
T. Claverie

Reputation: 12246

In golang, json.Marshal handles nested structs, slices and maps.

package main

import (
    "encoding/json"
    "fmt"
)

type Animal struct {
    Descr description `json:"description"`
    Age   int         `json:"age"`
}

type description struct {
    Name string `json:"name"`
}

func main() {
    d := description{"Cat"}
    a := Animal{Descr: d, Age: 15}
    data, _ := json.MarshalIndent(a,"", "  ")
    fmt.Println(string(data))
}

This code prints:

{
  "description": {
    "name": "Cat"
  },
  "age": 15
}

Of course, unmarshalling works the exact same way. Tell me if I misunderstood the question.

https://play.golang.org/p/t2CeHHoX72

Upvotes: 3

Related Questions