donglu2008 2016-09-22 23:44
浏览 89
已采纳

如何在Golang中将jsonb编码为http响应的一部分

I'm having a tough time moving json over the wire.

There is a jsonb field in a Postgres db that I need to add to a struct before sending it over the wire as an http response.

If the struct's payload field is a string, marshaling escapes the json like "{\"id\": \"3aa5fff0-ad91-41b1-84f0-d97f38e0e0f4\", \"user\": 1 }.

If the struct's payload field is a json.RawMessage, marshalling escapes the json as (what I imagine to be) a sequence of base64 encoded bytes.

This is the struct that I am marshaling and writing to the http response stream:

type NestJobReturn struct { Status string `json:"status"` Nest json.RawMessage `json:"nest"` }

I build a ret instance of this struct and print it out. If I use %v it shows bytes, and %s shows it as the proper, un-escaped json string:

log("Value of ret.Nest: %v", ret.Nest) // Value of ret.Nest: [123 34 105 ... log("Value of ret.Nest as a string: %s", ret.Nest) // Value of ret.Nest as a string: {"id": "f053...

Marshaling and i/o is done thusly:

js, _ := json.Marshal(ret) res.Header().Set("Content-Type", "application/json") res.Write(js)

The client currently receives the entire message looking kinda like this:

{"status":"ok","nest":"eyJpZCI6ICJmMD..."}

... but the intended value of "nest" is the valid json from my jsonb column in the database.

Any ideas?

  • 写回答

2条回答 默认 最新

  • doupian9798 2016-09-23 04:09
    关注

    You need to define the nested field as a pointer to json.RawMessage, e.g.

    type NestJobReturn struct {
        Status string           `json:"status"`
        Nest   *json.RawMessage `json:"nest"`
    }
    
    jsonStr := `{"type": "Object", "desc": "Simple nested object"}`
    raw := json.RawMessage(jsonStr)
    
    ret := NestJobReturn {
        Status: "DONE",
        Nest:   &raw,
    }
    

    A working example https://play.golang.org/p/Ju7kgbawss

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

报告相同问题?

悬赏问题

  • ¥15 WPF使用Canvas绘制矢量图问题
  • ¥15 用三极管设计一个单管共射放大电路
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 nirs_kit中打码怎么看(打码文件是csv格式)
  • ¥15 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题
  • ¥15 LCD12864中文显示
  • ¥15 在使用CH341SER.EXE时不小心把所有驱动文件删除了怎么解决
  • ¥15 gsoap生成onvif框架