dqtok88424 2015-05-15 10:58
浏览 356
已采纳

将结构体作为字符串存储在Redis中

As Redis only stores strings I would like to know how I can do the equivalent of Javascript's JSON.stringify using Go to convert a Struct into a string.

I have tried typecasting:

string(the_struct)

but this results in an error.

  • 写回答

1条回答 默认 最新

  • douyi7055 2015-05-15 11:04
    关注

    The encoding/json package can be used to easily convert a struct to JSON string and vice versa (parse a JSON string into a struct).

    Simple example (try it on the Go Playground):

    type Person struct {
        Name string
        Age  int
    }
    
    func main() {
        p := Person{"Bob", 23}
    
        // Struct -> JSON
        data, err := json.Marshal(&p)
        if err != nil {
            panic(err)
        }
        fmt.Println(string(data))
    
        // JSON -> JSON
        var p2 Person
        err = json.Unmarshal(data, &p2)
        if err != nil {
            panic(err)
        }
        fmt.Printf("%+v", p2)
    }
    

    Output:

    {"Name":"Bob","Age":23}
    {Name:Bob Age:23}
    

    Notes:

    The fields of the struct must be exported (start them with capital letter), else the json package (which uses reflection) will not be able to read/write them.

    You can also specify tags for the struct fields to control/fine tune the json marshaling/unmarshaling process, for example to change the names in the JSON text:

    type Person struct {
        Name string `json:"name"`
        Age  int    `json:"years"`
    }
    

    With this change the output of the above application is the following:

    {"name":"Bob","years":23}
    {Name:Bob Age:23}
    

    The documentation of the json.Marshal() function details the possibilities provided by the tags.

    And by implementing the json.Marshaler and json.Unmarshaler interfaces you can fully customize the marshaling / unmarshaling process.

    Also if your struct is not pre-defined (e.g. you don't know the fields in advance), you can use a map[string]interface{}. See this answer for details and examples.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?