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.

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

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?