Data Serialization and Deserialization

Learn how to communicate using JSON in the server’s REST APIs. Learn serialization and deserialization of JSON data to and from Go data structures.

Most modern APIs communicate in JSON. JSON stands for JavaScript Object Notation and is the format of choice for HTTP1.1 API communication as of today. A few legacy APIs still work on XML, but as of the time of writing this course, JSON stands as the gold standard. This means that both incoming requests and outgoing responses will communicate their data using this format.

JSON is native to JavaScript, meaning that it is how objects are natively represented in the JavaScript world. However, that is not necessarily true when writing code in other languages. Typed languages, like Java and Go, will require us to create classes or structs to store structured data. This means we must deserialize incoming JSON data to a struct of our definition. Once we are done processing and want to respond, we must take the data stored in our data structures (structs, arrays, or base types) and serialize and structure them to a meaningful JSON response object.

Let’s take a look at how we can do that.

Read JSON

Let’s say we want to be able to add a new user to our users resource. We must add a POST route, receive a JSON request body, deserialize it, and store it in a struct.

Step 1—Add a route

First, let’s add a route to receive an incoming POST request. It looks a lot like GET, except we use the Post() method of our router. Because it’s a POST request, we will receive data in the body of our request. We will read that using io.ReadAll(r.Body).

Get hands-on with 1200+ tech skills courses.