eva*_*nal 43

您真的只需要一个结构,并且如注释中所提到的,该字段上的正确注释将产生所需的结果.JSON不是一些非常变化的数据格式,它定义得很好,任何一个json,无论它多么复杂和混乱,都可以很容易地表示,并且通过模式和Go中的对象可以100%准确地表示大多数其他OO编程语言.这是一个例子;

package main

import (
    "fmt"
    "encoding/json"
)

type Data struct {
    Votes *Votes `json:"votes"`
    Count string `json:"count,omitempty"`
}

type Votes struct {
    OptionA string `json:"option_A"`
}

func main() {
    s := `{ "votes": { "option_A": "3" } }`
    data := &Data{
        Votes: &Votes{},
    }
    err := json.Unmarshal([]byte(s), data)
    fmt.Println(err)
    fmt.Println(data.Votes)
    s2, _ := json.Marshal(data)
    fmt.Println(string(s2))
    data.Count = "2"
    s3, _ := json.Marshal(data)
    fmt.Println(string(s3))
}
interface{}interface{}
  • 旁注:只有结构中的大写属性才会包含在 JSON 中。编组器将忽略私有属性 (2认同)