douwen2072 2015-12-15 14:40
浏览 671
已采纳

在golang中将字符串转换为json,反之亦然?

In my app, I receive a json from the client. This json can be anything since the user defines the keys and the values. In the backend I store it as string in the datastore.

Now i'm trying to override the MarshalJson / UnmarshalJson functions so that what I send / receive from the client is not a string but a json.

I can't figure out how to convert a string to json in go.

my structure

type ContextData string
type Iot struct {
Id              IotId       `json:"id,string" datastore:"-" goon:"id"`
Name            string   `json:"name"`
Context         ContextData  `json:"context" datastore:",noindex"` }

example of received data

{ 'id' : '',
  'name' '',
  'context': {
           'key1': value1,
           'key2': value2 }}

how i want to store this Context field in the datastore as a noindex string '{'key1':value1, 'key2':value2}' example of data i want to send

{ 'id' : '',
  'name' '',
  'context': {
           'key1': value1,
           'key2': value2 }}
  • 写回答

3条回答 默认 最新

  • dop2144 2015-12-15 17:25
    关注

    If I understand your problem correctly, you want to use json.RawMessage as Context.

    RawMessage is a raw encoded JSON object. It implements Marshaler and Unmarshaler and can be used to delay JSON decoding or precompute a JSON encoding.

    RawMessage is just []byte, so you can keep it in data store and then attach it for an outgoing messages as "precomputed JSON".

    type Iot struct {
        Id      int             `json:"id"`
        Name    string          `json:"name"`
        Context json.RawMessage `json:"context"` // RawMessage here! (not a string)
    }
    
    func main() {
        in := []byte(`{"id":1,"name":"test","context":{"key1":"value1","key2":2}}`)
    
        var iot Iot
        err := json.Unmarshal(in, &iot)
        if err != nil {
            panic(err)
        }
    
        // Context is []byte, so you can keep it as string in DB
        fmt.Println("ctx:", string(iot.Context))
    
        // Marshal back to json (as original)
        out, _ := json.Marshal(&iot)
        fmt.Println(string(out))
    }
    

    https://play.golang.org/p/69n0B2PNRv

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格