亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何格式化具有多個對象返回的 json 結構?(動態的)

如何格式化具有多個對象返回的 json 結構?(動態的)

Go
慕的地6264312 2021-11-01 17:03:33
我有一個 API 調用結果可以有多個返回我想知道結構應該是什么樣子,這是我到目前為止所擁有的,但它返回什么也沒有。type AssetInfo struct {    Result `json:"result"`}type Result struct {    Asset   map[string]Asset `json:"asset"`    Success bool             `json:"success,omitempty"`}type Asset struct {    IconUrl           string                   `json:"icon_url,omitempty"`    IconUrlLarge      string                   `json:"icon_url_large,omitempty"`    IconDragUrl       string                   `json:"icon_drag_url,omitempty"`    Name              string                   `json:"name,omitempty"`    MarketHashName    string                   `json:"market_hash_name,omitempty"`    MarketName        string                   `json:"market_name,omitempty"`    NameColor         string                   `json:"name_color,omitempty"`    BGColor           string                   `json:"background_color,omitempty"`    Type              string                   `json:"type,omitempty"`    Tradable          string                   `json:"tradable,omitempty"`    Marketable        string                   `json:"marketable,omitempty"`    Commodity         string                   `json:"commodity,omitempty"`    TradeRestrict     string                   `json:"market_tradeable_restriction,omitempty"`    FraudWarnings     string                   `json:"fraudwarnings,omitempty"`    Descriptions      map[string]*Descriptions `json:"descriptions,omitempty"`    OwnerDescriptions string                   `json:"owner_descriptions,omitempty"`    Tags              map[string]*Tags         `json:"tags,omitempty"`    ClassId           string                   `json:"classid,omitempty"`}type Descriptions struct {    Type    string `json:"type"`    Value   string `json:"value"`    Color   string `json:"color,omitempty"`    AppData string `json:"appdata"`}如果有人能告訴我我的結構有什么問題,那就太感謝了。這混淆我是怎么樣描述的回報不是可以范圍從0-20的數組,但多個對象,我怎么準備這一個結構時,我不知道有多少個對象要回報的東西,以及result可以返回多個"720616831"那么這應該怎么看?
查看完整描述

2 回答

?
FFIVE

TA貢獻1797條經驗 獲得超6個贊

你會因為第一個錯誤而自責——你的 JSON 有,result但你的 struct 標簽有response.


第二個問題比較棘手。問題是您聲明您的Asset地圖作為名為“資產”的鍵嵌套在結果中,但事實并非如此。其實它只是所有結果的按鍵其他比成功/錯誤。不幸的是,encoding/json沒有任何方式來表達這一點。你可以說它result是 a map[string]interface{},然后成功/錯誤(如果它們存在)將是 bool/string,并且資產將更多map[string]interface{}s 包含所有其他字段的鍵。這是可行的,但它有點丑陋/效率低下,如果您想轉換為適當的結構類型以便您可以在其上擁有方法,則需要做很多工作。


也許更好的方法是解碼成這種類型:


type AssetIntermediate struct {

    Result map[string]json.RawMessage `json:"result"`

}

以及擁有


type Asset struct { /* all those fields */ }

type AssetInfo struct {

    Success bool

    Error string

    Assets map[string]Asset

}

然后你可以做


var intermediate AssetIntermediate

err := json.Unmarshal(data, &intermediate)

/* handle err */


var ai AssetInfo


/* At this point, intermediate.Result is a map

 * of strings to json.RawMessage, which is just a []byte

 * containing not-yet-decoded JSON. We want to take

 * each field and put it into ai where it belongs.

 */

for k, v := range intermediate.Result {

    var err error

    // error and success keys are decoded into the respective fields

    if k == "error" {

        err = json.Unmarshal(v, &ai.Error)

    } else if k == "success" {

        err = json.Unmarshal(v, &ai.Success)

    } else {

        // Otherwise, we have an asset. First decode it...

        var asset Asset

        err = json.Unmarshal(v, &asset)

        if err == nil {

            // Create the Assets map if it doesn't exist yet

            if ai.Assets == nil {

                ai.Assets = map[string]Asset{}

            }

            // And store the asset in the map under the key k.

            ai.Assets[k] = asset

        }

    }

    /* handle err if non-nil */

}

這比一次Decode調用要多得多,但它基本上應該做正確的事情。


如果所有這些都在一個返回的函數中,(*AssetInfo, error)那么正確的替代方法/* Handle err */可能是


if err != nil {

    return nil, err

}


查看完整回答
反對 回復 2021-11-01
  • 2 回答
  • 0 關注
  • 214 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號