23/12/2019 - GO
This example maps multidimensional json to its struct representation in Golang. The json is coming as a request payload.
I am cutting corners here!
package league
import (
"encoding/json"
"net/http"
)
// -----------------------------------------------------------------------------
func Handle(rw http.ResponseWriter, rq *http.Request) {
var b reqBdy
d := json.NewDecoder(rq.Body)
d.DisallowUnknownFields()
_ = d.Decode(&b)
body, _ := json.Marshal(b)
rw.Header().Set("Content-Type", "application/json")
rw.Write(body)
}
// -----------------------------------------------------------------------------
type awards struct {
Type string `json:"type"`
Name string `json:"name"`
}
type address struct {
Line1 string `json:"line1"`
Line2 string `json:"line2"`
}
type reqBdy struct {
Name string `json:"name"`
Found uint16 `json:"found"`
Email string `json:"email"`
Address *address `json:"address"`
Awards []*awards `json:"awards"`
Sponsors []string `json:"sponsors"`
Random map[string]interface{} `json:"random"`
}
// Request
// Response
{
"name": "",
"found": 0,
"email": "",
"address": null,
"awards": null,
"sponsors": null,
"random": null
}
// Request
{
"name": "",
"found": "",
"email": "",
"address": "",
"awards": "",
"sponsors": "",
"random": ""
}
// Response
{
"name": "",
"found": 0,
"email": "",
"address": {
"line1": "",
"line2": ""
},
"awards": null,
"sponsors": null,
"random": null
}
// Request
{
"name": "Premier League",
"found": 1992,
"email": "contact@premierleague.com",
"address": {
"line1": "London",
"line2": "UK"
},
"awards": [
{
"type": "Ornament",
"name": "Trophy"
}
],
"sponsors": [
"Adidas",
"Nike",
"Umbro"
],
"random": {
"key1": "value1",
"key2": 123,
"key3": true,
"key4": false,
"key5": null
}
}
// Response
{
"name": "Premier League",
"found": 1992,
"email": "contact@premierleague.com",
"address": {
"line1": "London",
"line2": "UK"
},
"awards": [
{
"type": "Ornament",
"name": "Trophy"
}
],
"sponsors": [
"Adidas",
"Nike",
"Umbro"
],
"random": {
"key1": "value1",
"key2": 123,
"key3": true,
"key4": false,
"key5": null
}
}