首页 > 解决方案 > 转换仅包含 1 个数组字段的 JSON

问题描述

我正在尝试将仅包含 1 个字段的 JSON 转换为 Golang 中的复杂结构,但不幸的是我没有取回数据,相反,我得到了:

{Result:[]}

有谁知道为什么?(下面的代码)

package main

import (
    "encoding/json"
    "fmt"
)

type Account struct {
    AccountId string
}


type Response struct {
    Result []Account
}

func main() {
    input := []byte(`{
            "result": [
                {"account_id" : "1"},
                {"account_id" : "2"},
                {"account_id" : "3"},
            ]
        }

    `)

    var resp Response
    json.Unmarshal(input, &resp)
    fmt.Printf("%+v\n", resp)
}

标签: jsongo

解决方案


在您的结构类型中使用显式标记。

type Account struct {
    AccountId string `json:"account_id, omitempty"`
}

如果您是新手,请记住 JSON 大小,如果很大则使用流库(jstream 或 easyjson 等),其他建议是检查可空值或在它们为空时忽略它们,您可以使用可空库,如https:// github.com/guregu/null

干杯!


推荐阅读