![](/img/trans.png)
[英]Return HTTP-JSON data from asyncTask to Activity via listener
[英]golang - decode dynamic 'flat' http-json response
我試圖解析經典的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
}
這種情況下的困難在於響應是“平坦的”,如果它包含子元素,則解析是微不足道的,可能只是將其他結構作為子元素添加。
但是在這種情況下,我想避免構建包含每個可能屬性的超大型結構,並且我希望在不重復每個對象結構中的常量元素的情況下,將結構與對象類型分開。
這可能嗎?
一個可能的解決方案,現在我看到的可能是:
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"
}
]
}
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解析器將為您處理嵌套的struct,無需解析兩次。 但是您的json字符串需要匹配Go的struct結構。 像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`
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.