有一个 小 问题上的话题,但他们都不来覆盖我的情况,因此我创建一个新的.
我有以下JSON:
{"foo":{ "bar": "1", "baz": "2" }, "more": "text"}
Run Code Online (Sandbox Code Playgroud)
有没有办法解组嵌套的bar属性并将其直接分配给struct属性而不创建嵌套的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"`
}
Run Code Online (Sandbox Code Playgroud)
这是一个简化版本,请忽略详细程度.如您所见,我希望能够解析并赋值
// FooBar string `json:"foo.bar"`
Run Code Online (Sandbox Code Playgroud)
我见过人们使用地图,但那不是我的情况.我基本上不关心foo(这是一个大对象)的内容,除了一些特定的元素.
在这种情况下,正确的方法是什么?我不是在寻找奇怪的黑客,所以如果这是要走的路,那我很好.
Vol*_*ker 60
有没有办法解组嵌套的bar属性并将其直接分配给struct属性而不创建嵌套的struct?
不,encoding/json不能像"/ some> deep> childnode"这样的技巧,就像编码/ xml一样.嵌套结构是要走的路.
rex*_*das 29
就像Volker所提到的那样,嵌套结构是要走的路.但是如果你真的不想要嵌套结构,你可以覆盖UnmarshalJSON函数.
https://play.golang.org/p/dqn5UdqFfJt
type A struct {
FooBar string // takes foo.bar
FooBaz string // takes foo.baz
More string
}
func (a *A) UnmarshalJSON(b []byte) error {
var f interface{}
json.Unmarshal(b, &f)
m := f.(map[string]interface{})
foomap := m["foo"]
v := foomap.(map[string]interface{})
a.FooBar = v["bar"].(string)
a.FooBaz = v["baz"].(string)
a.More = m["more"].(string)
return nil
}
Run Code Online (Sandbox Code Playgroud)
请忽略我没有返回正确错误的事实.为简单起见,我把它留了下来.
更新:正确检索"更多"值.
Fra*_*nke 18
这是如何从Safebrowsing v4 API sbserver代理服务器解组JSON响应的示例: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)
}
Run Code Online (Sandbox Code Playgroud)
Him*_*shu 10
将nested的值分配json给struct,直到您知道json键的基础类型:-
package main
import (
"encoding/json"
"fmt"
)
// Object
type Object struct {
Foo map[string]map[string]string `json:"foo"`
More string `json:"more"`
}
func main(){
someJSONString := []byte(`{"foo":{ "bar": "1", "baz": "2" }, "more": "text"}`)
var obj Object
err := json.Unmarshal(someJSONString, &obj)
if err != nil{
fmt.Println(err)
}
fmt.Println("jsonObj", obj)
}
Run Code Online (Sandbox Code Playgroud)
小智 8
那匿名字段呢?我不确定这是否会构成“嵌套结构”,但比嵌套结构声明更干净。如果您想在其他地方重用嵌套元素怎么办?
type NestedElement struct{
someNumber int `json:"number"`
someString string `json:"string"`
}
type BaseElement struct {
NestedElement `json:"bar"`
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
81094 次 |
| 最近记录: |