- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
我 fork 了一个很棒的项目 here ,并且一直在学习一些东西。如果您看到 here,我无法弄清楚的问题是关于自定义解码的一些事情您可以看到这解码了 Thing
结构,它包含一个 Data interface{}
字段,然后使用 Kind string
字段解码。除了嵌套情况外,这一切都很好。所以最好的事情是一个例子:
只是说你有 Thing
结构,它是一个 listing
,因此 Thing.Data
被解码为类型 listing
。然后 listing
有 3 个类型为 link
的 Children
保存在 Children []Thing
字段中。这些 child 最终属于 map[string]interface {}
类型,这是我的问题。我怎样才能通过嵌套数据进行解码?这样 Children.Data
也被解码。有没有办法在 go 中执行此操作,还是我必须编写一个大循环或递归算法?请让我知道您的想法,或者我对这种情况的看法是否完全错误。谢谢
更新这是一个 json 示例
{
"kind": "Listing",
"data": {
"after": null,
"dist": 10,
"facets": {},
"modhash": null,
"whitelist_status": "all_ads",
"children": [
{
"kind": "t3",
"data": {
"domain": "self.nanocurrency",
"approved_at_utc": null,
"mod_reason_by": null,
"banned_by": null,
"num_reports": null,
"subreddit_id": "t5_2wlj3",
"thumbnail_width": null,
"subreddit": "CryptoCurrency",
"selftext_html": null,
"selftext": "",
"likes": null,
"suggested_sort": null,
"crosspost_parent_list": [
{
"domain": "self.nanocurrency",
"approved_at_utc": null,
"mod_reason_by": null,
"banned_by": null,
"num_reports": null,
"subreddit_id": "t5_4br49",
"thumbnail_width": null,
"subreddit": "nanocurrency",
"selftext_html": "<!-- SC_OFF --><div class=\"md\"><p>Seeing lots of comments about the lack of timestamps in the protocol, and just wanted to provide some information on why objectively accurate, global time timestamps are an illusion in decentralized systems. Logical time on the other hand is achievable and is in fact achieved in Nano via the individual block chains and the directed, acyclic graph (DAG). </p>\n\n<p>Generally, in a decentralized, distributed system, only logical time (C happened after B happened after A) can be agreed on globally (e.g. Lamport time: <a href=\"https://amturing.acm.org/p558-lamport.pdf\">https://amturing.acm.org/p558-lamport.pdf</a> or vector clocks). This is what the nano ledger does via chaining blocks, just as any other blockchain. Then it connects those chains via a DAG. Syncing global time to logical time is a hard problem that can either be approached via a consensus approach which is prone to sybil attacks, via a probabilistic approach which is what most blockchains go with - essentially relying on their peers - or a centralized approach like NTP which is a no-go in a decentralized system. If you&#39;re interested, check e.g. this paper: <a href=\"http://soft.vub.ac.be/%7Etvcutsem/distsys/clocks.pdf\">http://soft.vub.ac.be/~tvcutsem/distsys/clocks.pdf</a></p>\n\n<p>So what you&#39;re running into is the problem that while theoretically all or a relevant subset of nodes within the Nano or Bitcoin or Ethereum network could agree to call a certain time &quot;Monday February 12 2018 20:35:23&quot;, this timestamp could still be incorrect vs the outside world.</p>\n\n<p>That&#39;s why any accurate global timestamps in software today rely on centralized information and trusted entities. The only way this can change is if machines start setting their clocks on their own accurately (e.g. chip-scale atomic clocks)</p>\n\n<p>Some people think this is bad news for Nano because in traditional blockchain, timestamps are fairly important because they are used in new block validation: <a href=\"http://culubas.blogspot.co.uk/2011/05/timejacking-bitcoin_802.html\">http://culubas.blogspot.co.uk/2011/05/timejacking-bitcoin_802.html</a> . Timestamps are a blessing and a curse at the same time in blockchain: They allow for timing and validation of blocks and therefore regulation of coin mining, but also allow for timestamp double spend attacks. Since Nano does not use mining, it is not susceptible to those attacks.</p>\n\n<p>Even with the relative importance of time and timestamps in Bitcoin, timestamp in Bitcoin are not guaranteed to be corresponding to logical time on the chain. Here&#39;s the bitcoin wiki talking about the bitcoin block timestamp: <a href=\"https://en.bitcoin.it/wiki/Block_timestamp\">https://en.bitcoin.it/wiki/Block_timestamp</a> </p>\n\n<blockquote>\n<p>A timestamp is accepted as valid if it is greater than the median timestamp of previous 11 blocks, and less than the network-adjusted time + 2 hours. &quot;Network-adjusted time&quot; is the median of the timestamps returned by all nodes connected to you. As a result, block timestamps are not exactly accurate, and they do not even need to be in order. Block times are accurate only to within an hour or two. </p>\n</blockquote>\n\n<p>This is probably as good as it gets. Still no ordering guarantees though, and a possibilities for attacks which have been discussed again and again. There are certain guards in Bitcoin code to prevent these from happening. </p>\n\n<p>So if you have somebody lecturing you about how architecturally superior coins would have a accurate and monotonically increasing timestamps, point them here, or here: <a href=\"https://cointelegraph.com/news/timestamp-hacking-debunking-the-myth-of-precision-timestamps\">https://cointelegraph.com/news/timestamp-hacking-debunking-the-myth-of-precision-timestamps</a></p>\n\n<p>Would timestamps be convenient to have on the protocol? Yes, and that would likely be a good reason to include them. Are timestamps accurately depicting global time, and can they be used as evidence in any chain? No they can&#39;t.</p>\n\n<p>Why are we seeing inaccurate timestamps in the block explorer? Because these are kept in a db outside of the ledger and have been set January 19. Nothing more to it.</p>\n\n<p>Why do people like to babble about how this is a weakness in Nano? No clue.</p>\n</div><!-- SC_ON -->",
"selftext": "Seeing lots of comments about the lack of timestamps in the protocol, and just wanted to provide some information on why objectively accurate, global time timestamps are an illusion in decentralized systems. Logical time on the other hand is achievable and is in fact achieved in Nano via the individual block chains and the directed, acyclic graph (DAG). \n\nGenerally, in a decentralized, distributed system, only logical time (C happened after B happened after A) can be agreed on globally (e.g. Lamport time: https://amturing.acm.org/p558-lamport.pdf or vector clocks). This is what the nano ledger does via chaining blocks, just as any other blockchain. Then it connects those chains via a DAG. Syncing global time to logical time is a hard problem that can either be approached via a consensus approach which is prone to sybil attacks, via a probabilistic approach which is what most blockchains go with - essentially relying on their peers - or a centralized approach like NTP which is a no-go in a decentralized system. If you're interested, check e.g. this paper: http://soft.vub.ac.be/~tvcutsem/distsys/clocks.pdf\n\nSo what you're running into is the problem that while theoretically all or a relevant subset of nodes within the Nano or Bitcoin or Ethereum network could agree to call a certain time \"Monday February 12 2018 20:35:23\", this timestamp could still be incorrect vs the outside world.\n\nThat's why any accurate global timestamps in software today rely on centralized information and trusted entities. The only way this can change is if machines start setting their clocks on their own accurately (e.g. chip-scale atomic clocks)\n\nSome people think this is bad news for Nano because in traditional blockchain, timestamps are fairly important because they are used in new block validation: http://culubas.blogspot.co.uk/2011/05/timejacking-bitcoin_802.html . Timestamps are a blessing and a curse at the same time in blockchain: They allow for timing and validation of blocks and therefore regulation of coin mining, but also allow for timestamp double spend attacks. Since Nano does not use mining, it is not susceptible to those attacks.\n\nEven with the relative importance of time and timestamps in Bitcoin, timestamp in Bitcoin are not guaranteed to be corresponding to logical time on the chain. Here's the bitcoin wiki talking about the bitcoin block timestamp: https://en.bitcoin.it/wiki/Block_timestamp \n\n> A timestamp is accepted as valid if it is greater than the median timestamp of previous 11 blocks, and less than the network-adjusted time + 2 hours. \"Network-adjusted time\" is the median of the timestamps returned by all nodes connected to you. As a result, block timestamps are not exactly accurate, and they do not even need to be in order. Block times are accurate only to within an hour or two. \n\nThis is probably as good as it gets. Still no ordering guarantees though, and a possibilities for attacks which have been discussed again and again. There are certain guards in Bitcoin code to prevent these from happening. \n\nSo if you have somebody lecturing you about how architecturally superior coins would have a accurate and monotonically increasing timestamps, point them here, or here: https://cointelegraph.com/news/timestamp-hacking-debunking-the-myth-of-precision-timestamps\n\nWould timestamps be convenient to have on the protocol? Yes, and that would likely be a good reason to include them. Are timestamps accurately depicting global time, and can they be used as evidence in any chain? No they can't.\n\nWhy are we seeing inaccurate timestamps in the block explorer? Because these are kept in a db outside of the ledger and have been set January 19. Nothing more to it.\n\nWhy do people like to babble about how this is a weakness in Nano? No clue.",
"likes": null,
"suggested_sort": null,
"user_reports": [],
"secure_media": null,
"is_reddit_media_domain": false,
"link_flair_text": null,
"id": "7ww6bm",
"banned_at_utc": null,
"mod_reason_title": null,
"view_count": null,
"archived": false,
"clicked": false,
"media_embed": {},
"report_reasons": null,
"author": "ohlookaballoon",
"num_crossposts": 2,
"saved": false,
"mod_reports": [],
"can_mod_post": false,
"is_crosspostable": true,
"pinned": false,
"score": 24,
"approved_by": null,
"over_18": false,
"hidden": false,
"thumbnail": "self",
"edited": false,
"link_flair_css_class": null,
"author_flair_css_class": null,
"contest_mode": false,
"gilded": 0,
"downs": 0,
"brand_safe": false,
"secure_media_embed": {},
"removal_reason": null,
"author_flair_text": null,
"stickied": false,
"can_gild": true,
"thumbnail_height": null,
"parent_whitelist_status": null,
"name": "t3_7ww6bm",
"spoiler": false,
"permalink": "/r/nanocurrency/comments/7ww6bm/why_global_time_objectively_accurate_timestamps/",
"subreddit_type": "public",
"locked": false,
"hide_score": false,
"created": 1518417258,
"url": "https://www.reddit.com/r/nanocurrency/comments/7ww6bm/why_global_time_objectively_accurate_timestamps/",
"whitelist_status": null,
"quarantine": false,
"title": "Why global time, objectively accurate timestamps are not achievable in decentralized systems",
"created_utc": 1518388458,
"subreddit_name_prefixed": "r/nanocurrency",
"ups": 24,
"media": null,
"num_comments": 18,
"is_self": true,
"visited": false,
"mod_note": null,
"is_video": false,
"distinguished": null
}
],
"user_reports": [],
"secure_media": null,
"is_reddit_media_domain": false,
"link_flair_text": null,
"id": "7x3r45",
"banned_at_utc": null,
"mod_reason_title": null,
"view_count": null,
"archived": false,
"clicked": false,
"media_embed": {},
"report_reasons": null,
"author": "ohlookaballoon",
"num_crossposts": 0,
"saved": false,
"mod_reports": [],
"can_mod_post": false,
"is_crosspostable": true,
"pinned": false,
"score": 2,
"approved_by": null,
"over_18": false,
"hidden": false,
"thumbnail": "default",
"edited": false,
"link_flair_css_class": null,
"author_flair_css_class": "New",
"contest_mode": false,
"gilded": 0,
"downs": 0,
"brand_safe": true,
"secure_media_embed": {},
"removal_reason": null,
"author_flair_text": "Redditor for 27 days.",
"stickied": false,
"can_gild": true,
"thumbnail_height": null,
"parent_whitelist_status": "all_ads",
"name": "t3_7x3r45",
"crosspost_parent": "t3_7ww6bm",
"spoiler": false,
"permalink": "/r/CryptoCurrency/comments/7x3r45/why_global_time_objectively_accurate_timestamps/",
"subreddit_type": "public",
"locked": false,
"hide_score": false,
"created": 1518496223,
"url": "https://np.reddit.com/r/nanocurrency/comments/7ww6bm/why_global_time_objectively_accurate_timestamps/",
"whitelist_status": "all_ads",
"quarantine": false,
"title": "Why global time, objectively accurate timestamps are not achievable in decentralized systems",
"created_utc": 1518467423,
"subreddit_name_prefixed": "r/CryptoCurrency",
"ups": 2,
"media": null,
"num_comments": 0,
"is_self": false,
"visited": false,
"mod_note": null,
"is_video": false,
"distinguished": null
}
},
最佳答案
这正是json.RawMessage是为了(查看文档中的解码示例)。首先解码 JSON 对象的顶层,检查类型字段,然后解码数据字段:
type Listing struct {
WhitelistStatus string `json:"whitelist_status"`
Children []Thing `json:"children"`
}
type T3 struct {
Domain string `json:"domain"`
CrosspostParentList []struct {
Domain string `json:"domain"`
} `json:"crosspost_parent_list"`
}
type Thing struct {
Kind string `json:"kind"`
Data interface{} `json:"data"`
}
func (t *Thing) UnmarshalJSON(b []byte) error {
var step1 struct {
Kind string `json:"kind"`
Data json.RawMessage `json:"data"`
}
if err := json.Unmarshal(b, &step1); err != nil {
return err
}
var step2 interface{}
switch step1.Kind {
case "Listing":
step2 = &Listing{}
case "t3":
step2 = &T3{}
default:
return errors.New("unknown kind: " + step1.Kind) // or simply ignore
}
if err := json.Unmarshal(b, step2); err != nil {
return err
}
t.Kind = step1.Kind
t.Data = step2
return nil
}
在 Playground 上试试:https://play.golang.org/p/giBVT2IWPd-
关于go - 如何解码嵌套的未知字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49741594/
我有一个交叉表函数,我过去曾多次成功使用它,但现在它在最后转储所有数据,而不是将其旋转到输出表中。它似乎无法找到交叉表。我通过以下方式对其进行了研究; 如果 tablefunc 不存在则创建扩展; -
表1(客户表) Id, CustomerId, IsKnownCustomer,phonemacaddress 1, 空 0 00:9a:34:cf:a4 2, 004024 1 00:6f:64:c
知道为什么我总是收到这个烦人且无用的错误代码/描述吗? Failed to pull image myapidemodocker.azurecr.io/apidemo:v4.0: rpc error:
我正在进行 PHP 登录,并且之前可以正常工作,但我尝试使用户名功能不区分大小写,但此后代码一直无法正常工作。我删除了我添加的所有内容,以尝试使其不区分大小写,即 strtolower()。页面上显示
有人会帮助我提供有关此错误的任何可能信息吗?原因?登录?在哪里寻找/开始? Cannot use output buffering in output buffering display handl
我已经添加了这样的脚本 我在我的 test.js 中做了这个 var app = angular.module('MyApp', ['ngRoute']).config
关闭。这个问题需要更多focused .它目前不接受答案。 想改进这个问题吗? 更新问题,使其只关注一个问题 editing this post . 关闭 8 年前。 Improve this qu
我有这个sql语句: selectAllUsersByCriteria = 连接.prepareStatement( “从用户那里选择*?=?” ); 下面的方法运行该语句: public Array
我有一个白色的 EditText,在 Android 3.1 及更高版本中,光标不显示(因为它也是白色的)。有关信息,我使用 android:background="@android:drawable
我正在尝试使用 Keras 实现深度学习模型。但是我有一个未知形状实现的问题。我一直在寻找类似的错误,但没有找到。 这是我的代码。 Xhome = dataset[:,32:62] Xaway = d
关注此introduction可以通过导入命名空间 System.Xml 来使用 XMLReader 类。在我的 Visual Studio 项目中,我使用 .NET 4.0,但 System.Xml
我有一个动态链接库的程序。该程序将函数指针传递给该库以执行。 但是 ubsan(Undefined Behavior Sanitizer)指定指针位于错误的函数类型上。那只会发生 如果回调函数有一个类
我正在尝试在我的 Swift SpriteKit 应用程序中使用 AVAudioSession。我遇到了奇怪的“未声明类型”问题。例如…… import AVFoundation var audioS
如果在编译期间(在实际编译和运行程序之前)其参数之一的值已知/未知,如何专门化模板函数? 我还不知道怎么做。 想法 1: #include #include int main(void){
我看到一些人的代码是这样的: while (!(baseType == typeof(Object))) { .... baseType = baseType.BaseType;
我正在尝试使用 GoColly 框架获取所有 HREF 链接,但是只允许任何域的 url 为根 URL 或子域(否路径)。我已经注释掉了我的 REGEXP。文件扩展名没有事情。我只是在“/”之后不想要
我有一个包含多个实体的数据库,特别是 Book 和 User。它们之间存在这样的 ManyToMany 关系: 书: @Entity @Table(name = "Books") public cla
如果我将范围的初始部分设置为 Range("A:A"),如何确保将整行传递给排序? 数据 id、fname、mname、lname、后缀、状态、位置、时区 通过在 id 中搜索起点和终点来选择范围。
我对kubernetes很陌生,而对于docker来说就不那么多了。 我一直在研究示例,但是我对自动缩放器(似乎无法缩放)感到困惑。 我在这里通过示例https://kubernetes.io/doc
我在 ChildWindow 中使用 SL Toolkit 5 中的 BusyIndicator 控件。 在某些解决方案中,它可以工作,但在其他解决方案中,使用完全相同的代码(至少看起来),我在运
我是一名优秀的程序员,十分优秀!