原来我写了自己的库来做到这一点:https ://github.com/joeshaw/json-lossless
它建立在go-simplejson之上,每当结构被编组或解组时,将解析的 JSON 状态保持simplejson.Json
在它和结构之间的代理状态。
示例用法:
package main
import (
"encoding/json"
"fmt"
"time"
"github.com/joeshaw/json-lossless"
)
type Person struct {
lossless.JSON `json:"-"`
Name string `json:"name"`
Age int `json:"age"`
Birthdate time.Time `json:"birthdate"`
}
func (p *Person) UnmarshalJSON(data []byte) error {
return p.JSON.UnmarshalJSON(p, data)
}
func (p Person) MarshalJSON() []byte, error) {
return p.JSON.MarshalJSON(p)
}
var jsondata = []byte(`
{"name": "David Von Wolf",
"age": 33,
"birthdate": "1980-09-16T10:44:40.295451647-04:00",
"phone": "614-555-1212"}
`)
func main() {
var p Person
err := json.Unmarshal(jsondata, &p)
if err != nil {
panic(err)
}
// Set values on the struct
p.Age++
// Set arbitrary keys not in the struct
p.Set("title", "Chief Wolf")
fmt.Printf("%#v\n", p)
data, err := json.Marshal(p)
if err != nil {
panic(err)
}
fmt.Println(string(data))
}
打印件(为便于阅读而格式化):
main.Person{JSON:lossless.JSON{json:(*simplejson.Json)(0x21020a190)},
Name:"David Von Wolf",
Age:34,
Birthdate:time.Time{sec:62473560280,
nsec:295451647,
loc:(*time.Location)(0x16de60)}}
{"age":34,
"birthdate":"1980-09-16T10:44:40.295451647-04:00",
"name":"David Von Wolf",
"phone":"614-555-1212",
"title": "Chief Wolf"}