A better way to unmarshall JSON array intro struct?

blov · · 437 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Hello everyone! Even do I have been following go and this community since it inception, I didn&#39;t have a change to work on a proper project until recently. My current understanding of it, it&#39;s quite limited but at least I find myself very productive.</p> <p>On the project I&#39;m working, I have the following problem, any ideas/suggestions will be very appreciated:</p> <p>I&#39;m querying an API that it&#39;s responding with a JSON array of arrays. The internal array values have meaning, but the keys are stripped for efficiency I suppose. This is the best I have come up with:</p> <p><a href="https://play.golang.org/p/RjotQpLZpqC" rel="nofollow">https://play.golang.org/p/RjotQpLZpqC</a></p> <p>Basically, embed a struct into another struct and add a custom UnmarshalJSON() to convert the array to JSON object with numeric string keys and then go via encoding/json unmarshall again to take advantage of the annotations. One of the reasons to do this, it&#39;s because I will need to do it with multiple structs.</p> <p>Edit: added some extra information.</p> <hr/>**评论:**<br/><br/>nsd433: <pre><p>You seem to be using data -&gt; JSON -&gt; data2 as a way of type cast fields. That works, but it&#39;s going to be slow.</p> <p>The only alternative I can think of is to do the casts in Go, like this:</p> <p><a href="https://play.golang.org/p/XHFTc_Pmbvm" rel="nofollow">https://play.golang.org/p/XHFTc_Pmbvm</a></p></pre>jfcalcerrada: <pre><p>Sorry, forgot to mention it! One of the reasons to use that custom UnmarshalJSON it&#39;s because I&#39;ll need to do it with many other struct. That&#39;s why I wanted to avoid the casting and use tags.</p></pre>danredux: <pre><p>I see two things...</p> <p>First, create an array pointing to all the places you want the values unmarshalled to. This avoids double allocation, or &#34;temporarily&#34; holding values and putting them in the right place.</p> <p>Second, your float64 is coming from a string, so make a custom type that has that behaviour so you can use it anywhere you need it.</p> <p><a href="https://play.golang.org/p/SBmrYa6CSyP" rel="nofollow">https://play.golang.org/p/SBmrYa6CSyP</a></p></pre>jfcalcerrada: <pre><p>This looks more interesting... One of the reasons for the UnmarshalJSON it&#39;s because I&#39;ll need to do it for several other struct. I&#39;ll add it to the post.</p> <p>But this might be a good compromise.</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

437 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传