在Golang中解析JSON时,字符串为nil。

huangapple go评论87阅读模式
英文:

string is nil when unmarshaling json in Golang

问题

我正在尝试在Golang中解组一个JSON,它的结构如下:

{"graph":[[1650970800,1859857],[1650972600,1918183]...],"records":246544,"period":"24h","zone":"test.com","queries":93321}

虽然我可以解组一些值,但其他值却是空的,比如zonegraph(但这些值在JSON中是有的)。以下是我的代码:

type NSoneResponse struct {
    Graphs  []Graph
    Records int64
    Period  string
    Zones   string
    Queries int64
}

type Graph struct {
    Timestamp int64
    Queries   int64
}

const (
    zoneUsageUrl = "https://api.nsone.net/v1/stats/usage/test.com?period=24h&networks=*"
)

func main() {
    getUsageData(zoneUsageUrl)
}

func getUsageData(url string) {
    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        log.Fatal(err)
    }

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        log.Fatal(err)
    }
    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        panic(err)
    }

    var filteredData []NSoneResponse
    err = json.Unmarshal([]byte(body), &filteredData)
    if err != nil {
        panic(err)
    }

    for i := range filteredData {
        fmt.Printf("Quieries per timestamp: %v\nRecords count: %v\nPeriod: %v\nZone: %v\nNumber of queries: %v\n", filteredData[i].Graphs, filteredData[i].Records, filteredData[i].Period, filteredData[i].Zones, filteredData[i].Queries)
    }
}

最后的输出结果为:

Quieries per timestamp: []
Record count: 243066
Period: 24h
Zone:
Number of queries: 91612963

当我尝试在NSoneResponse结构体中使用指针时,这些值返回的是nil(注意-Period键也包含字符串值,但它不返回nil):

Quieries per timestamp: <nil>
Quota count: 0xc000274470
Period: 0xc000460310
Zone: <nil>
Number of queries: 0xc000274488

我做错了什么?

英文:

I'm trying to unmarshal a json in Golang, which looks like this:

{&quot;graph&quot;:[[1650970800,1859857],[1650972600,1918183]...],&quot;records&quot;:246544,&quot;period&quot;:&quot;24h&quot;,&quot;zone&quot;:&quot;test.com&quot;,&quot;queries&quot;:93321} 

While I can unmarshal some of the values, others are simply empty i.e zone or graph (but those values are returned in the Json). Here's my code

type NSoneResponse struct {
Graphs  []Graph
Records int64
Period  string
Zones   string
Queries int64
}

type Graph struct {
	Timestamp int64
	Queries   int64
}

const (
	zoneUsageUrl  = &quot;https://api.nsone.net/v1/stats/usage/test.com?period=24h&amp;networks=*&quot;
)

func main() {
	getUsageData(zoneUsageUrl)
}

func getUsageData(url string) {
	req, err := http.NewRequest(&quot;GET&quot;, url, nil)
	if err != nil {
		log.Fatal(err)
	}

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		panic(err)
	}

	var filteredData []NSoneResponse
	err = json.Unmarshal([]byte(body), &amp;filteredData)
	if err != nil {
		panic(err)
	}

	for i := range filteredData {
		fmt.Printf(&quot;Quieries per timestamp: %v\nRecords count: %v\nPeriod: %v\nZone: %v\nNumber of queries: %v\n&quot;, filteredData[i].Graphs, filteredData[i].Records, filteredData[i].Period, filteredData[i].Zones, filteredData[i].Queries)

	}
}

The output at the end

Quieries per timestamp: []
Record count: 243066
Period: 24h
Zone:
Number of queries: 91612963

When I tried to use pointers in the NSoneResponse struct, I got nil for those values instead (note - the Period key also contains string value, yet it does not return nil)

Quieries per timestamp: &lt;nil&gt;
Quota count: 0xc000274470
Period: 0xc000460310
Zone: &lt;nil&gt;
Number of queries: 0xc000274488  

What am I doing wrong?

答案1

得分: 1

首先,我将解释一下你代码中的错误。你应该使用struct tags,因为你的结构体中的Graphs变量与你的JSON中的graph不相等,这个错误也存在于zone变量中。将你的结构体改为以下形式:

type NSoneResponse struct {
    Graphs  [][]int `json:"graph"`
    Records int64   `json:"records"`
    Period  string  `json:"period"`
    Zones   string  `json:"zone"`
    Queries int64   `json:"queries"`
}

此外,你的JSON中有一个int数组,而不是对象数组,所以你必须更改Graphs的类型。之后,你需要将int数组转换为图形数组。

英文:

first of all, I will explain the mistake in your code, you should use struct tags. because your Graphs variable of your struct is not equal of graph in your json, this mistake is on zone variable too. change your struct to this :

type NSoneResponse struct {
	Graphs  [][]int `json:&quot;graph&quot;`
	Records int64   `json:&quot;records&quot;`
	Period  string  `json:&quot;period&quot;`
	Zones   string  `json:&quot;zone&quot;`
	Queries int64   `json:&quot;queries&quot;`
}

also, your JSON has an array of int not an array of Objects, so you must change the type of Graphs. after that, you should convert the array of int to an array of graphs.

huangapple
  • 本文由 发表于 2022年4月28日 21:31:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/72044588.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定