Saturday, December 3, 2016

Converting JSON to a Slice in Golang


*This tutorial does not cover coding up a simple webserver, but that is implicitly part of my explanation. However, you do not need a webserver component to use the instructions below. You can 'mock' the API call to the webserver using a simple function that returns a pre-made JSON string.
What: Parsing a JSON object into a slice in GO/Golang.
Why: I've been working on a pet project and wanted to learn a couple technologies that were new to me. I decided I wanted to build a web service that has an outward facing API for handling queries and uploads for a database. Because I had used XML in the past, and found it a little too verbose, I wanted to learn about and use JSON for this project. Once I received the JSON from the user, I could parse it into an instance of my class and then use it programmatically.
Procedure: In order to accomplish this, we will need to code up a few things. First, we need a class that represents the JSON object you are expecting to handle. Here is a simple class we can use for our example:


type MyOptionClass struct {
    Name string `json:"name"`
    Option string `json:"option"`
}
Additionally, here is a JSON string representing two of MyOptionClass objects:


[
  {
    "name":"optionname1",
    "option":"pushLevelUp"
  },
  {
    "name":"optionname2",
    "option":"pullLevelDown"
  },
]
Next, we need a function that is going to parse the JSON object that is retrieved from the API call by the user. Let's say, for example sake, that our API receives any amount of JSON objects. The following function can then parse that JSON into class instances that we can work with programmatically:


func ParseJson(jsonObj []byte) {
    var optionClassArray *[]MyOptionClass
    ...
    json.Unmarshal(jsonObj, &optionClassArray)
    for _, val := range *optionClassArray {
        NewMyOptionClass(val.Name, val.Option)
        ... or do something else with val ...
    }
}
The important stuff to note is the specifics of what type of objects we are passing to the Unmarshal call. During my trials, I found that it works best to send the address of a variable which is of type pointer to an array of your class type. That's hard to follow, but if you refer to the example above, you'll get it.
From this point you could append each class instance to a slice and return it, print out the values of the json object, or anything else.
Common Errors:
  1. Unmarshal isn't parsing any of the fields from the JSON into your class:
    1. Solution: Validate the JSON being sent from the client using an online validator.
  2. Some of the fields are blank in your class instances parsed from the JSON:
    1. Solution: Make sure your JSON fields and Class/Struct fields are the same/line up.
Good luck!
*Disclaimer: I do not own the images that compose the banner image. If you hold the rights and would like me to remove the images, please contact me and I will do so.

No comments:

Post a Comment