-3

I have a json.Unmarshal in a Golang file which decodes JSON data sent from a Swift program. The code properly decodes r.Body into a String (newStr is the exact same as the string I redeclare it as). However, the json.Unmarshal line doesn't seem to work for no good reason, and even my teacher can't figure it out. Any ideas?

The code:

buf := new(bytes.Buffer)
buf.ReadFrom(r.Body)
newStr := buf.String()
fmt.Println(newStr)
var data Teacher

newStr = `{"body":"How are you all today?","id":283,"title":"Hello World","userID":238"}`

json.Unmarshal([]byte(newStr), &data)

fmt.Println(data.body)

My struct:

// Teacher struct:
type Teacher struct {
    body   string `json:"body"`
    id     int    `json:"id"`
    title  string `json:"title"`
    userID int    `json:"userID"`
}

Any ideas? I'm totally lost. Thanks!

  • It's a good idea to run `go vet` command on a regular basis. The command reports the unexported fields with a `json` struct tag. – Bayta Darell May 06 '20 at 13:07

1 Answers1

2

Capitalize names of Teacher struct fields.

type Teacher struct {
    Body   string `json:"body"`
    Id     int    `json:"id"`
    Title  string `json:"title"`
    UserID int    `json:"userID"`
}
Eklavya
  • 1
  • 4
  • 21
  • 46
  • 1
    Also remove the trailing `"` in `"userID": 238"`. And don't ignore the error returned by `json.Unmarshal` – Marc May 06 '20 at 12:16