4

I'm a newbie to beego trying to get a JSON response on a route.

I have a controller defined as such.

package controllers

import (
    "github.com/astaxie/beego"
)

type ErrorController struct {
    beego.Controller
}

type ErrorJson struct {
    s string
    d string
}

func (this *ErrorController) Get() {

    var responseJson ErrorJson
    responseJson = ErrorJson{
        s: "asdf",
        d: "qwer",
    }

    this.Data["json"] = responseJson
    this.ServeJson()
}

My router is defined as

beego.Router("/api", &controllers.ErrorController{})

When I visit the route, I get an Empty JSON object without any properties.

{}

If I replace the json struct with a string, I get a response. So beego is aware of the controller and the method.

this.Data["json"] = "Hello World"

What am I doing wrong?

GokulSrinivas
  • 383
  • 2
  • 10
  • 1
    Possible duplicate of [Go json.Marshal(struct) returns "{}"](http://stackoverflow.com/questions/26327391/go-json-marshalstruct-returns) – Charlie Tumahai Dec 07 '15 at 06:01
  • The same question here: https://stackoverflow.com/questions/8270816/converting-go-struct-to-json – Bruce Jan 03 '18 at 03:26

2 Answers2

9

You need to export the fields in ErrorJson by starting the name with an uppercase character. Use field tags to specify the lowercase names in the output.

type ErrorJson struct {
    S string `json:"s"`
    D string `json:"d"`
}

The encoding/json package and similar packages ignore unexported fields.

Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242
1

The s & d, low case in golang is not visable.

Bryce
  • 3,046
  • 2
  • 19
  • 25