将多维json映射到Golang中的结构表示

298 阅读1分钟

这个例子将多维json映射到Golang中的结构表示。json是作为一个请求的有效载荷而来。

HTTP处理程序

我在这里偷工减料了!

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