-3

I runned the bellow code to retrieve a json from api and parse the values to a struct to use the values, but the print appears in blank.

The json format is:

"user":{
      "id":13,
      "name":"xpto",
      "email":"bla@blum.com.br",
      "role":"partner"
   },
   "token":"hjhfsdhfjkhskfjhsjkfhjksdhfjkshfkjsoiwwsnskcnksjcjkscksjcksbsdsdjsdj"
}

and the code that i am running is:

package main

import (
    "bytes"
    "encoding/json"
    "io/ioutil"
    "net/http"
)

type resposta struct {
    usuario usuario `json:"user"`
    token   string  `json:"token"`
}

type usuario struct {
    id    string `json:"id"`
    name  string `json:"name"`
    email string `json:"email"`
    role  string `json:"role"`
}

func main() {
    values := map[string]string{"email": "blablum@xpto.com.br", "password": "senhaaaaa"}
    jsonValue, _ := json.Marshal(values)

    response, _ := http.Post("https://api.endereco.com.br/sessions", "application/json", bytes.NewBuffer(jsonValue))

    defer response.Body.Close()
    body, _ := ioutil.ReadAll(response.Body)

    println(body)
    println(string(body))

    var result resposta
    json.Unmarshal(body, &result)

    println("Resposta")
    println(result.token)
    println(result.token)

}

Any suggestion?

  • Does this answer your question? [(un)marshalling json golang not working](https://stackoverflow.com/questions/25595096/unmarshalling-json-golang-not-working). This is probably the most common question/mistake relating to go + json. – msanford Mar 30 '22 at 19:35

1 Answers1

-2

All your struct fields are unexported (they begin with a lowercase letter) and thus are considered "private." This is preventing the json package from seeing them with reflection. Export your fields by naming them with a Capital letter and it'll work.

Here's an example with some test data: https://go.dev/play/p/0lWdLtNuOr3

Corey Ogburn
  • 24,072
  • 31
  • 113
  • 188