topic上有a few questions,但似乎没有一个覆盖我的情况,因此我正在创建一个新的。
我有如下的JSON:
{"foo":{ "bar": "1", "baz": "2" }, "more": "text"}
有没有一种方法可以解组嵌套的bar属性,并将其直接分配给struct属性,而无需创建嵌套结构?
我现在采用的解决方案如下:
type Foo struct {
More String `json:"more"`
Foo struct {
Bar string `json:"bar"`
Baz string `json:"baz"`
} `json:"foo"`
// FooBar string `json:"foo.bar"`
}
这是一个简化版本,请忽略详细信息。如您所见,我希望能够解析并将值赋给
// FooBar string `json:"foo.bar"`
我见过有人用地图,但这不是我的情况。我基本上不关心foo
(它是一个大对象)的内容,除了一些特定的元素。
在这种情况下,正确的方法是什么?我不是在寻找奇怪的黑客,因此,如果这是一条可行的道路,我可以接受。
发布于 2016-06-06 20:50:39
这是一个如何从Safebrowsing JSON API sbserver代理服务器解组v4响应的示例:https://play.golang.org/p/4rGB5da0Lt
// this example shows how to unmarshall JSON requests from the Safebrowsing v4 sbserver
package main
import (
"fmt"
"log"
"encoding/json"
)
// response from sbserver POST request
type Results struct {
Matches []Match
}
// nested within sbserver response
type Match struct {
ThreatType string
PlatformType string
ThreatEntryType string
Threat struct {
URL string
}
}
func main() {
fmt.Println("Hello, playground")
// sample POST request
// curl -X POST -H 'Content-Type: application/json'
// -d '{"threatInfo": {"threatEntries": [{"url": "http://testsafebrowsing.appspot.com/apiv4/ANY_PLATFORM/MALWARE/URL/"}]}}'
// http://127.0.0.1:8080/v4/threatMatches:find
// sample JSON response
jsonResponse := `{"matches":[{"threatType":"MALWARE","platformType":"ANY_PLATFORM","threatEntryType":"URL","threat":{"url":"http://testsafebrowsing.appspot.com/apiv4/ANY_PLATFORM/MALWARE/URL/"}}]}`
res := &Results{}
err := json.Unmarshal([]byte(jsonResponse), res)
if(err!=nil) {
log.Fatal(err)
}
fmt.Printf("%v\n",res)
fmt.Printf("\tThreat Type: %s\n",res.Matches[0].ThreatType)
fmt.Printf("\tPlatform Type: %s\n",res.Matches[0].PlatformType)
fmt.Printf("\tThreat Entry Type: %s\n",res.Matches[0].ThreatEntryType)
fmt.Printf("\tURL: %s\n",res.Matches[0].Threat.URL)
}
发布于 2016-11-27 19:37:53
发布于 2015-11-22 05:43:17
那么匿名域呢?我不确定这是否会构成“嵌套结构”,但它比拥有嵌套结构声明要干净得多。如果您想在其他地方重用嵌套的元素,该怎么办?
type NestedElement struct{
someNumber int `json:"number"`
someString string `json:"string"`
}
type BaseElement struct {
NestedElement `json:"bar"`
}
https://stackoverflow.com/questions/21268000
复制相似问题