Trying to use a Struct with a variable named "type" for JSON

272 views
Skip to first unread message

pop...@gmail.com

unread,
Jan 22, 2017, 3:39:56 PM1/22/17
to golang-nuts
Below is a snippet of my code. I need to pass a json body that has a field name "type" in it. I can create the body as a string, but I was trying to leverage structs. Obviously, trying to create a variable named 'type' in the struct throws errors. As "type" as a field name is common in json, I was wondering how others have solved for this situation. I have been googling for possible solutions, but finding the right mix of search terms has proven challenging.


package main

import (
"fmt"
"encoding/json"
)

type LoginRequest struct {
username string
password string
}

func createsession() {
_, err := resty.R().
SetHeader("Content-Type", "application/json").
SetBody(`{"type": "APISession","version": {"type": "APIVersion","major": 1,"minor": 6,"micro": 0}}`).
if err != nil {
panic(err)
}
}

func login() {
_, err := resty.R().
SetHeader("Content-Type", "application/json").
SetBody(LoginRequest{username: "my_admin", password: "testing123"}).
//SetBody(`{"type": "LoginRequest","username": "my_admin","password": "testing123"}` //this works
}

func main ()
    createsession()
    login()

Tamás Gulácsi

unread,
Jan 22, 2017, 3:48:33 PM1/22/17
to golang-nuts, pop...@gmail.com
TL;DR; use struct tags to specify marshal/unmarsal names.

type LoginRequest struct {
User string `json:"username"`
Passw string `json:"password"`
}

...

SetBody(struct {
  Type string `json:"type"`
  LoginRequest
}{
  Type: "LoginRequest", LoginRequest:{User:"my_admin", Passw:"testing123"}})



Matt Harden

unread,
Jan 22, 2017, 6:53:00 PM1/22/17
to Tamás Gulácsi, golang-nuts, pop...@gmail.com
Note that you can't use lowercase struct field names with encoding/json anyway, because fields must be exported for encoding/json to see them, and fields are exported by starting them with an uppercase letter. So if you want the JSON field names to be lower case, you have to use struct tags. I think that while Tamás's solution should work, you probably just want the type field to be in LoginRequest itself:

type LoginRequest struct {
Type string `json:"type"`
User     string `json:"username"`
Password string `json:"password"`
}


--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Adam Bowen

unread,
Jan 29, 2017, 9:18:40 AM1/29/17
to Matt Harden, Tamás Gulácsi, golang-nuts
Sweet. Thanks gents. Still fairly new to Golang.

I followed Matt's example and was able to get it working. 

To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages