Chandan Kumar
Chandan Kumar

Reputation: 899

GoLang JSON payload preparation with multiple data

I want to create JSON payload in given below format. I want a code or pattern that prepares the given format.

{
    transactiontype: 'DDDDD'
    emailType: 'QQQQQQ'
    template: {
        templateUrl: 'xry.kk'
        templateName: 'chanda'
    }
    date: [
        {
            UserId: 1
            Name: chadnan
        },
        {
            UserId: 2
            Name: kkkkkk
        }
    ]
}

Upvotes: 0

Views: 1113

Answers (3)

ASHWIN RAJEEV
ASHWIN RAJEEV

Reputation: 2891

// Transaction is a struct which stores the transaction details
type Transaction struct {
    TransactionType string   `json:"transaction_type"`
    EmailType       string   `json:"email_type"`
    Template        Template `json:"template"`
    Date            []Date   `json:"date"`
}

//Template is a struct which stores the template details
type Template struct {
    TemplateURL  string `json:"template_url"`
    TemplateName string `json:"template_name"`
}

// Date is a struct which stores the user details
type Date struct {
    UserID int    `json:"user_id"`
    Name   string `json:"name"`
}

Above given structs are the correct data structure for storing your json body you can use json decoder for perfectly storing the data into struct

func exampleHandler(w http.ResponseWriter, r *http.Request) {
    var trans Transaction
    decoder := json.NewDecoder(r.Body)
    err := decoder.Decode(&trans)
    if err != nil {
        log.Println(err)
    }
}

Upvotes: 1

r3vit
r3vit

Reputation: 83

You can use an online tool to convert a json into a valid Go struct: https://mholt.github.io/json-to-go/

Given your JSON, the Go struct is:

type AutoGenerated struct {
    Transactiontype string `json:"transactiontype"`
    EmailType       string `json:"emailType"`
    Template        struct {
        TemplateURL  string `json:"templateUrl"`
        TemplateName string `json:"templateName"`
    } `json:"template"`
    Date []struct {
        UserID int    `json:"UserId"`
        Name   string `json:"Name"`
    } `json:"date"`
}

After the conversion, use the json.Marshal (Go Struct to JSON) and json.Unmarshal (JSON to Go Struct)

Complete example with your data: https://play.golang.org/p/RJuGK4cY1u-

Upvotes: 1

Black_Dreams
Black_Dreams

Reputation: 610

Hope this helps :

type Template struct {
TemplateURL string `json:"templateUrl" param:"templateUrl"`
TemplateName string `json:"templateName" param:"templateName"`
}

type Date struct {
UserId string `json:"UserId" param:"UserId"`
Name string `json:"Name" param:"Name"`
}
type NameAny struct {
*Template
TransactionType string `json:"transactiontype" param:"transactiontype"`
EmailType string `json:"emailType" param:"emailType"`
Data []Date `json:"date" param:"date"`
}
Data, _ := json.Marshal(NameAny)
Json(c, string(Data))(w, r)

Upvotes: 1

Related Questions