1

How do I go about consuming the following json post in Go?

{
    "notificationType": "email",
    "client": "The CLient",
    "content": "Hellow World",
    "recipients": [
        {
            "address": "[email protected]"
        },
        {
            "address": "[email protected]"
        }
    ]
}

I've managed to get the string types but I really don't know enough about Go to deal with the recipients array.

My code looks like this:

package handlers

import (
    "net/http"
    "encoding/json"
    "notificationservice/src/validation"
    "io/ioutil"
    "fmt"
)

func EmailHandler(w http.ResponseWriter, r *http.Request) {
    b, err := ioutil.ReadAll(r.Body)
    defer r.Body.Close()
    if err != nil {
        http.Error(w, err.Error(), 500)
        return
    }

    var postData validation.EmailValidator
    err = json.Unmarshal(b, &postData)
    if err != nil {
        http.Error(w, err.Error(), 500)
        return
    }

    fmt.Println(postData.Client)
    fmt.Println(postData.Content)
}

My struct:

package validation

import "fmt"

type EmailValidator struct {
    Client  string `json:"client"`
    Content string `json:"content"`
    //Recipients []string `json:"recipients"`
}

func (validator * EmailValidator) ValidateEmail() (bool) {

    var required = []string {validator.Client, validator.Content, validator.Stuff}

    for _, param := range required {
        fmt.Println(param)
    }
    return true;
}

I've tried setting Recipients to []string and [][]string but I really don't know what I'm doing.

In PHP I would use the var_dump command to print out the entire object and debug step by step from there, but Go doesn't appear to have that functionality.

3 Answers 3

4

You can try something like this:

package main

import (
    "encoding/json"
    "fmt"
)

type Email struct {
    Adress string `json:"address"`
}

type EmailValidator struct {
    Client  string `json:"client"`
    Content string `json:"content"`
    Recipients []Email `json:"recipients"`
}

func main() {
    j := `{
    "notificationType": "email",
    "client": "The CLient",
    "content": "Hellow World",
    "recipients": [
        {
            "address": "[email protected]"
        },
        {
            "address": "[email protected]"
        }
    ]
    }`
    result := EmailValidator{}
    json.Unmarshal([]byte(j), &result)
    fmt.Printf("%+v", result) // something like var_dump in PHP
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answers, but this is still not working. Could it be because 'address' is in it's own anonymous object?
@user1894292 If you run code from my answer you receive: {Client:The CLient Content:Hellow World Recipients:[{Adress:[email protected]} {Adress:[email protected]}]}. Isn't result correct? What do you mean by 'address' is in it's own anonymous object? Do you have another JSON format?
2

You need an array of "things with an address":

type EmailValidator struct {
    Client  string `json:"client"`
    Content string `json:"content"`
    Recipients []Recipient `json:"recipients"`
}


type Recipient struct {
    Address string `json:"address"`
}

4 Comments

Thanks for your answers, but this is still not working. Could it be because 'address' is in it's own anonymous object?
So maybe your JSON data isn't how you expect it to be. Try to print your HTTP response body to make sure it looks the way you expect. For the JSON example you mentioned, this code does work.
How would you print HTTP response body? When I try to print the raw response, I get what looks like a hex string.
When you used ioutil.ReadAll, you got a byte slice. Convert it to string with string(b).
1

You can nest objects, and Unmarshal will handle the entire tree for you.

type Recipient struct {
    Address string `json:"address"`
}

type EmailValidator struct {
    Client  string `json:"client"`
    Content string `json:"content"`
    Recipients []Recipient `json:"recipients"`
}

The rest of your code looks good.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.