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 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。