Marshal and unMarshal of Struct to JSON in Golang

marshall-and-unmarshalling-golang

The Marshaling use to convert Go object into JSON and Unmarshal is JSON to Go Struct. This golang tutorial help to understand marshalling and un-marshalling of data using Golang. We can encode and decode struct data using golang marshal and unmarshal.

We will convert struct type data into JSON by marshaling and JSON to string using unmarshalling process. The marshal and Unmarshal method returned response in Bytes types, but we can change these data to strings/JSON in Go.

JSON is very commonly data format to exchange information between client and server.This is a language-independent data format and can use in any programming interface API.

The golang is having 'encoding/json' package for json related operation into the go application.This package is providing many powerful and useful method. The JSON parsing and generating JSON data is easily available in many programming languages.

Golang Marshal Struct to json

The json package provides a json.Marshal() method.This method help to convert Struct into json data, This method takes object as a param and returned Bytes code.We will create simple Post struct, that have title, post and updated_by property.

type Post struct {
Title string
Post string
Updated_by string
}

Let’s convert Posts struct data into json using json.Marshal() method.The below code use to convert Struct data into Byte code using golang marshaling.

post_obj := Posts{Title:"test", Post:"test desc", Updated_by :"rozi"}
post, _ := json.Marshal(post_obj)
fmt.Println(string(post))

The above code will output below response –

{"Title":"test", "Post":"test desc", "Updated_by" :"rozi"}

Un-marshalling in GOLANG

The json.Unmarshal() method is used to convert json into Struct Object, This method takes json byte data as a parameter and returned struct object as a response.

I am taking below json string and convert into byte data, Finally convert json byte data into Posts struct.

 {"title":"test", "content":"test desc", "updated_by" :"rozi"}

The Posts struct have Title, Post and Updated_by property.The string keys in the JSON are matched to the field names in the structs.

Let’s create Response Struct that will use to match byte code using unmarshal.

type Response struct {
Title string json:"title"
Post string json:"content"
Updated_by string json:"updated_by"
}

Now, We will convert below json string byte data and convert into Post struct using json.Unmarshal() method.

bytes := []byte(str_post)
var res Response
json.Unmarshal(bytes, &res)
fmt.Println(res.Title)

The Output :
test

In the above code, first converted json string into byte code, then created empty Response struct and assign res variable.Then we have called Unmarshal method by passing a pointer to an empty structs.Finally, Print the Struct Title value.