在Go中的JSON请求中使用嵌套数组

时间:2018-07-03 12:12:07

标签: go

我该如何在Go中使用以下json帖子?

{
    "notificationType": "email",
    "client": "The CLient",
    "content": "Hellow World",
    "recipients": [
        {
            "address": "email1@example.com"
        },
        {
            "address": "email2@example.com"
        }
    ]
}

我设法获取了字符串类型,但是我真的对Go不够了解,无法处理收件人数组。

我的代码如下:

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)
}

我的结构:

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;
}

我尝试将收件人设置为[] string和[] [] string,但是我真的不知道自己在做什么。

在PHP中,我将使用var_dump命令打印出整个对象并从那里逐步调试,但是Go似乎没有该功能。

3 个答案:

答案 0 :(得分:4)

您可以尝试以下操作:

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": "email1@example.com"
        },
        {
            "address": "email2@example.com"
        }
    ]
    }`
    result := EmailValidator{}
    json.Unmarshal([]byte(j), &result)
    fmt.Printf("%+v", result) // something like var_dump in PHP
}

答案 1 :(得分:2)

您需要一个“带有地址的事物”数组:

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


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

答案 2 :(得分:1)

您可以嵌套对象,Unmarshal将为您处理整个树。

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

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

其余代码看起来不错。