04 How to know Decode JSON
Introduction to JSON Decoding
In the previous article we learned to encode JSON and how to create a JSON object, so next we will learn how to translate JSON objects into struct objects in Golang. We often call this conversion from JSON into a Golang struct object as decode.
In Golang, to do this conversion or also known as decode we will use a function.
1json.Unmarshal(byte[],interface{})The function above has 2 parameters, namely
byte[]is the data from JSON to be convertedinterface{}is a place to store the results of the conversion in the form of struct pointers that we create in Golang.
How to Implement
Have you started to imagine, friends? OK, we will try to create a function that can convert data from JSON objects into struct objects in Golang. Here, friends, try creating the function below.
1func ConvertObjectJSON(data string) Customer {
2 var cust Customer
3 err := json.Unmarshal([]byte(data), &cust)
4 if err != nil {
5 panic(err)
6 }
7
8 return cust
9}Look at the function above, it will be seen that because the data is of type string we need to convert it first into bytes using []byte(data), then we will store the results of the conversion in a struct that has been initialized in the variable cust.
Because must the pointer be sent? Unmarshal will convert the JSON byte data and send the value into a pointer variable so that there are no nil variables. So the required pointer of a variable will allocate memory for non-nil storage. In the documentation explanation it is like this.
And the way the unmarshal works is like this
Next, we will test the function above by creating a unit test as below.
1func TestConvertObjectJSON(t *testing.T) {
2 type args struct {
3 data string
4 }
5 tests := []struct {
6 name string
7 args args
8 want Customer
9 }{
10 {
11 name: "success conversion object JSON",
12 args: args{
13 data: string(`{"first_name":"Santekno","middle_name":"Ihsan","last_name":"Arif"}`),
14 },
15 want: Customer{
16 FirstName: "Santekno",
17 MiddleName: "Ihsan",
18 LastName: "Arif",
19 },
20 },
21 }
22 for _, tt := range tests {
23 t.Run(tt.name, func(t *testing.T) {
24 if got := ConvertObjectJSON(tt.args.data); !reflect.DeepEqual(got, tt.want) {
25 t.Errorf("ConvertObjectJSON() = %v, want %v", got, tt.want)
26 }
27 })
28 }
29}