(un)marshalling json golang not working

Solution 1:

For example,

package main

import "fmt"
import "encoding/json"

type testStruct struct {
    Clip string `json:"clip"`
}

func main() {
    //unmarshal test
    var testJson = "{\"clip\":\"test\"}"
    var t testStruct
    var jsonData = []byte(testJson)
    err := json.Unmarshal(jsonData, &t)
    if err != nil {
        fmt.Printf("There was an error decoding the json. err = %s", err)
        return
    }
    fmt.Printf("contents of decoded json is: %#v\r\n", t)

    //marshal test
    t.Clip = "test2"
    data, err := json.Marshal(&t)
    if err != nil {
        fmt.Printf("There was an error encoding the json. err = %s", err)
        return
    }
    fmt.Printf("encoded json = %s\r\n", string(data))
}

Output:

contents of decoded json is: main.testStruct{Clip:"test"}
encoded json = {"clip":"test2"}

Playground:

http://play.golang.org/p/3XaVougMTE

Export the struct fields.

type testStruct struct {
    Clip string `json:"clip"`
}

Exported identifiers

An identifier may be exported to permit access to it from another package. An identifier is exported if both:

  • the first character of the identifier's name is a Unicode upper case letter (Unicode class "Lu"); and
  • the identifier is declared in the package block or it is a field name or method name.

All other identifiers are not exported.

Solution 2:

Capitalize names of structure fields

type testStruct struct {
    clip string `json:"clip"` // Wrong.  Lowercase - other packages can't access it
}

Change to:

type testStruct struct {
    Clip string `json:"clip"`
}

Solution 3:

In my case, my struct fields were capitalized but I was still getting the same error. Then I noticed that the casing of my fields was different. I had to use underscores in my request.

For eg: My request body was:

{
  "method": "register",
  "userInfo": {
    "fullname": "Karan",
    "email": "[email protected]",
    "password": "random"
  }
}

But my golang struct was:

type AuthRequest struct {
    Method   string   `json:"method,omitempty"`
    UserInfo UserInfo `json:"user_info,omitempty"`
}

I solved this by modifying my request body to:

{
  "method": "register",
  "user_info": {
    "fullname": "Karan",
    "email": "[email protected]",
    "password": "random"
  }
}