将类型转换为结构的编组流

将类型转换为结构的编组流

本文介绍了将类型转换为结构的编组流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在处理进入应用程序的json对象流,并且在弄清楚解析它们的最佳方法时遇到了一些困难.流由具有已定义类型的对象组成.问题在于对象中的字段之一的类型正在更改.看起来像这样:

I'm currently dealing with a stream of json objects coming in to my application, and am having some difficulties figuring out what the best way of parsing them is. The stream consists of objects that have a defined type. The problem is that one of the fields in the object is of changing type. It looks like this:

[{
  "status": "closed",
  "type": "transaction",
  "transaction": {
    "TransactionType": "TypeA",
    "Account": "Some string",
    "Fee": "14",
    "date": 45325680
  },
  "validated": true
},

{
  "status": "closed",
  "type": "transaction",
  "transaction": {
    "TransactionType" : "TypeB",
    "Account" : "Some string",
    "Fee": "42",
    "Destination" : "Some string"
  },
  "validated": true
}]

您可以看到父级"没有变化,但事务"却发生了变化.我从事务"字段中删除了很多字段,以使其更易于解释,但这是一种具有10种常见字段和10种变化字段的类型,这些类型取决于该类型.还有10种事务类型,这使得将所有内容放入一个结构并具有大量的可选字段变得很烦人.我还在考虑为每种事务类型使用一个结构,但这是行不通的,因为那样便无法指定字段在父级中应具有的类型.

You can see that the "parent" does not change, but the "transaction" does. I removed a lot of fields from the "transaction" field to make it easier to explain, but this is a type with 10-ish common fields and 10-ish changing fields that are dependent on the type. There are also 10 transaction types, this makes it pretty annoying to put everything into one struct and have a ton of optional fields. I was also thinking about one struct for every transaction type, but this does not work because then there is no way of specifying which type the field should have in the parent.

我将如何有效地解析这些对象?不幸的是,我无法更改流中出现的元素的结构.解决此问题的最佳方法是什么?

How would I parse these objects effectively? Unfortunately, I can't change the structure of the elements coming out of the stream. What would be the best way to solve this?

推荐答案

我认为使用反射是 [] map [string] interface {}

并且在此答案我举了一个有关使用反射来解码变化类型的示例.

And in this answer I had gave an example about using reflect to decode changing type.

这篇关于将类型转换为结构的编组流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!