<p>Hey there!</p>
<p>As the title states, is Unmarshal possible to one of X given formats?</p>
<p>Example:</p>
<p>The setlist.fm API always returns a result or an error.
I've set both types as structs in Go however to deal with errors can I specify two models Unmarshal should try to work with?</p>
<hr/>**评论:**<br/><br/>shovelpost: <pre><p>What you want to do is check the HTTP request status code. If it is not in between the limits of 200 and 299 then you have an error so you Decode to the error struct.</p></pre>CritJongUn: <pre><p>Thank you!</p></pre>everdev: <pre><p>Any decent API should have a 1:1 mapping of responses to status codes for each endpoint, so this shouldn't be an issue for APIs.</p>
<p>Approaching the problem in a more general way, you could also Unmarshal the data into a struct. If required values are missing, then Unmarshal your second struct. Repeat until you get a populated struct.</p></pre>shovelpost: <pre><p>Usually when we are talking about a simple and well-designed API, as you mentioned, we are talking about 1:1 mapping. Each endpoint returns a standard response. But it can also return a standard error. This does not need a more generic and complex solution.</p></pre>happycynic: <pre><p>I would like to know how to accomplish this when you can't know what the JSON schema is prior to reading the JSON.</p></pre>tv64738: <pre><p><a href="http://eagain.net/articles/go-dynamic-json/" rel="nofollow">http://eagain.net/articles/go-dynamic-json/</a> might help.</p></pre>joncalhoun: <pre><blockquote>
<p>you can't know what the JSON schema is prior to reading the JSON.</p>
</blockquote>
<p>Do you know the JSON will be one of several formats and you just need to read a field to find out which format, or what?</p>
<p>If the former, check out this article: <a href="https://blog.gopheracademy.com/advent-2016/advanced-encoding-decoding/#encoding-and-decoding-generics:ed675bd476e2bd7c07a2d82583157710" rel="nofollow">https://blog.gopheracademy.com/advent-2016/advanced-encoding-decoding/#encoding-and-decoding-generics:ed675bd476e2bd7c07a2d82583157710</a></p>
<p>It isn't generics in the sense that has been debated a lot in Go lately, but refers to generics as in multiple different JSON formats that vary based on the object's type. Something like this could possibly be adapted for your needs.</p></pre>: <pre><p>[deleted]</p></pre>CritJongUn: <pre><p>?</p></pre>Killing_Spark: <pre><p>Im afraid you need to determin yourself which format youre dealing with. You can probably do a few contains() to determin it? </p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传