4

I'm using Go and GoRestful to program a RESTFUL front end to some entities stored on Google App Engine Datastore.

The data is turned into JSON/XML and presented to the user with tags controlling the style for each format. How can I also apply tags to the name of the struct itself so it is output using the correct style?

An example of my structs would be:

type Shallow struct {
    Key          string    `datastore:"-" json:"key" xml:"key"`
    LastModified time.Time `json:"last_modified" xml:"last-modified"`
    Version      int       `json:"version" xml:"version"`
    Status       int       `json:"status" xml:"status"`
    Link         Link      `datastore:"-" json:"link" xml:"link"`
    Name         string    `json:"name" xml:"name"`
}

type ProbabilityEntry struct {
    ItemId      int64   `datastore:"ItemId" json:"item_id" xml:"item-id"`
    Probability float32 `datastore:"Probability" json:"probability" xml:"probability"`
    Quantity    int16   `datastore:"Quantity" json:"quantity" xml:"quantity"`
}

type LootTable struct {
    Shallow
    AllowPreload  bool               `json:"allow_preload" xml:"allow-preload"`
    Probabilities []ProbabilityEntry `json:"probabilities" xml:"probabilities"`
}

When the LootTable struct emits to JSON/XML it should represent itself as 'loot_table' or 'loot-table' rather than 'LootTable'.

4

1 回答 1

4

简单的回答:

将其包装在外部结构中:

type Payload struct {
   Loot LootTable `json:"loot_table"`
}

更长的答案:

如果 JSON 的接收者知道他们得到了什么,那么这并不是必需的。但是,在构建 JSON API 时,我经常创建一个 Response 结构,其中包含有关请求的额外详细信息,其中可能包括响应的类型。这是一个例子:

type JSONResponse struct {
   Obj    interface{} `json:"obj"`    // Marshall'ed JSON (not wrapped)
   Type   string      `json:"type"`   // "loot_table" for example
   Ok     bool        `json:"ok"`     // Does this response require error handling?
   Errors []string    `json:"errors"` // Any errors, you could leave out Ok and just check this
}

同样,通过 API 调用,您通常知道您期望什么,但如果响应可能是多种类型之一,则此方法可以提供帮助。

于 2014-01-05T13:46:25.643 回答