<p>I'm trying to pass an array of bytes to a client in a JSON object. Here's the struct I'm trying to marshal:</p>
<pre><code>type SomeResponse struct {
data []byte `json:"data"`
}
</code></pre>
<p>So here's my code creating the struct and marshaling it:</p>
<pre><code>bytes := getSomeBytes() // returns somewhat large []byte
someResponse := SomeResponse{data: bytes}
jsonResponse, err := json.Marshal(someResponse)
</code></pre>
<p>There are no errors returned from json.Marshal. However when I print the jsonResponse, it's a tiny []byte with a length of 2. Why is my data not there?</p>
<hr/>**评论:**<br/><br/>wwader: <pre><p>Try rename data to Data with capital d to make it public</p></pre>aminoglycine: <pre><p>Thank you! I guess it makes sense that if you made an attribute private, you wouldn't want it potentially being sent out the door. Duh.</p></pre>throwlikepollock: <pre><p>I don't know if it's a "feature" or not, i had always assumed that it's simply because the json.* lib cannot access/view private variables. To put it differently, i don't think it's a security feature of the marshal/unmarshal, i think it's the general private/public feature of the language.</p></pre>j_d_q: <pre><p>The marshaller uses reflection, so it definitely has access to variables that aren't exported. But as a language construct it makes sense not to Marshal private fields so that (like you mentioned) it is aligned with how the rest of the language works</p>
<p>Let's say, for example, you get a struct from a library that describes a user. The fields are id, name and email. It also has secretKey as a private field. Would you want it included if you marshalled the struct? It's information that your app didn't even know existed on the struct, but it's somehow showing up in the json</p></pre>throwlikepollock: <pre><p>I decided to look it up and try to figure out how to actually get private fields content. Based on <a href="http://stackoverflow.com/a/17982725/6189743" rel="nofollow">this</a> comment it sounds like it's quite difficult (ie, supported via "normal" reflect methods) to get the content.</p>
<p>Do you disagree? I was having trouble doing it without the pointer hackery.</p></pre>j_d_q: <pre><p>It's not terribly difficult. <a href="https://play.golang.org/p/NJ721P5ZL_" rel="nofollow">Here's a short example</a></p></pre>throwlikepollock: <pre><p>Yea i knew it used reflection, i just didn't think those were available. Good to know they are! I've used reflection in the past and swore i couldn't access private fields haha</p></pre>dirkharrington: <pre><p>fwiw this behavior is documented and is w.a.i.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传