2017-08-23 04:51
浏览 10


I have a struct of called class like this.

type ClassDetails struct {
ClassNumber int `json:"classNumber"`
Names []string `json:names`}

I have manually created something like this.

type Subject struct {
Math ClassDetails `json:"math"`
Science ClassDetails `json:"science"`}

I want to do this on the fly. Add more ClassDetails to the Subject as I get information, but I cannot use an array of type class. How can this be done? And I also need to add the names of the classes as the json tag. My resultant struct should hold values like this.

    "classes": {
        "school": "MayorWestHigh",
        "math": [{
                "classNumber": "1",
                "names": ["aaron", "baron", "cathy"]
                "classNumber": "2",
                "names": ["aaron", "baron", "cathy"]
        "science": [{
            "classNumber": "1",
            "names": ["ted", "baron", "isiah"]
        "geography": [{
            "classNumber": "1",
            "names": ["peter", "glen", "joe"]

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douyue1998
    douyue1998 2017-08-23 05:26

    Instead of statically defining each subject, how about simply using a map from subject name => array of class details ?

    One way you can get very close to the JSON you want by using a map like I described above, and by embedding the map into a struct as follows:

    type ClassDetails struct {
        ClassNumber int      `json:"classNumber"`
        Names       []string `json:names`
    type Subjects map[string][]ClassDetails
    type Classes struct {
        School string `json:"school"`

    An instance of the Classes struct above would fill in the following part of your desired JSON:

      "classes": {
        ... the Classes instance goes here...

    The remaining outer object can just be constructed as follows:

    c := Classes{...}
    outer := map[string]Classes{"classes": c}

    A JSON marshal of the outer object, with the right data initialized, arrives at almost exactly your JSON above (to match it exactly you'd have to turn the ClassNumber into a string type).

    Here is a Go Playground link that initializes these structs with the exact data you want and pretty-prints your JSON:

    EDIT: This still doesn't exactly match the JSON in your question, as it will add a new object in there called "Subjects". The problem is that the object inside of "classes" in your JSON mixes types, and Go can't declare dynamic struct fields.

    If you really have to use that JSON structure, you'll need to go with the more generic map[string]interface{} to allow mixed types at the same level in your object hierarchy. Here's another Go Playground link that has the correct implementation:

    点赞 评论