Unmarshaling nested JSON objects

后端 未结 8 1814
轻奢々
轻奢々 2020-11-27 11:37

There are a few questions on the topic but none of them seem to cover my case, thus I\'m creating a new one.

I have JSON like the following:

{\"foo\"         


        
8条回答
  •  伪装坚强ぢ
    2020-11-27 11:43

    This is an example of how to unmarshall JSON responses from the Safebrowsing v4 API sbserver proxy server: 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)
    }
    

提交回复
热议问题