golang - 解码动态'平'的http-json响应

时间:2015-06-25 08:08:30

标签: json parsing go orientdb

我试图在经典的go-struct中解析动态的http-json响应。我正在使用orient-db,问题如下:

  • 每个对象都有静态元素
  • 每个对象都有自定义属性

例如,伪结构响应可以是:

type orientdb_reply struct {
  # the "statics" elements that we always have
  element_type string   `json:"@type"`
  rid          string   `json:"@rid"`
  version      int      `json:"@version"`
  class        string   `json:"@class"`

  # then we have custom attributes for each object

  # for example, object 'server' can have
  hostname     string   `json:"hostname"`
  ip           string   `json:"ip"`

  # object 'display' can have
  model         string  `json:"model"`
  serial_number string  `json:"serial_number"`
  resolution    string  `json:"resolution"`

  # and so on
}

在这种情况下的困难是响应是“平坦的”,如果它包含子元素,则分辨率很小,并且可以简单地添加其他结构作为子元素。

但在这种情况下,我想避免构建一个包含每个可能属性的巨大的结构,并且我希望将结构保持为对象类型,而不重复每个object-struct中的常量元素。

这可能吗?

一种可能的解决方案,现在我看到可能是:

type constant_fields struct {
  # the "constants" elements that we ever have
  element_type string   `json:"@type"`
  rid          string   `json:"@rid"`
  version      int      `json:"@version"`
  class        string   `json:"@class"`
}

type server_fields struct {
  constants     constant_fields
  # for example, object 'server' can have
  hostname     string   `json:"hostname"`
  ip           string   `json:"ip"`
}

type display_fields struct {
  constants     constant_fields
  # object 'display' can have
  model         string  `json:"model"`
  serial_number string  `json:"serial_number"`
  resolution    string  `json:"resolution"`
}

但这意味着我应该解析每个请求两次(一个用于常量的东西,另一个用于属性的东西)。而且我不知道解析器是否喜欢json中不存在的“奇怪”结构(constant_fields)。

真实的例子:

{
   "result" : [
      {
         "name" : "cen110t",
         "guest_state" : "running",
         "@type" : "d",
         "guest_mac_addr" : "XX:XX:XX:XX:XX:XX",
         "@version" : 1,
         "hostname" : "",
         "vm_uid" : "vm-29994",
         "guest_ip" : "10.200.1.92",
         "vm_type" : "VirtualMachine",
         "@rid" : "#13:103",
         "guest_family" : "linuxGuest",
         "storage_type" : "",
         "guest_fullname" : "CentOS 4/5/6/7 (64-bit)",
         "@class" : "VM"
      }
   ]
}

1 个答案:

答案 0 :(得分:1)

I would like avoid to build a mega-huge struct that contains each possible attribute

在结构定义中使用json.RawMessage作为属性类型,然后该属性将保持原始状态而不进行解析。

I would like to keep the structure separate for object-type without repeating the statics element in each object-struct

因为你可以在struct中嵌套struct,就像json对象中的json对象一样。将common(statics)属性放在一个json对象中并嵌套它是一种好方法。

to the question update

是的,它会起作用。 json解析器将为您处理嵌套结构,不需要解析两次。但是你的json字符串需要与Go的结构结构相匹配。像json

{
    "k1":"v1",
    "k2":{
        "k21":"v21"
    }
}

将匹配go struct:

type nest_struct struct{
    K21 string `k21`
}

type top struct{
    K1 string `k1`,
    K2 nest_struct `k2`
}