如何使用多个对象返回格式化json结构? (动态)

时间:2015-08-29 01:05:20

标签: json struct go

我有一个API调用,它返回如下:

{
    "result": {
        "720268538": {
            "icon_url": "-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXU5A1PIYQNqhpOSV-fRPasw8rsUFJ5KBFZv668FFEuh_KQJTtEuI63xIXbxqOtauyClTMEsJV1jruS89T3iQKx_BBqa2j3JpjVLFH1xpp0EQ",
            "icon_url_large": "",
            "icon_drag_url": "",
            "name": "Chroma Case",
            "market_hash_name": "Chroma Case",
            "market_name": "Chroma Case",
            "name_color": "D2D2D2",
            "background_color": "",
            "type": "Base Grade Container",
            "tradable": "1",
            "marketable": "1",
            "commodity": "1",
            "market_tradable_restriction": "7",
            "fraudwarnings": "",
            "descriptions": {
                "0": {
                    "type": "html",
                    "value": " ",
                    "app_data": ""
                },
                "1": {
                    "type": "html",
                    "value": "Container Series #38",
                    "color": "99ccff",
                    "app_data": ""
                },
                "2": {
                    "type": "html",
                    "value": " ",
                    "app_data": ""
                },
                "3": {
                    "type": "html",
                    "value": "Contains one of the following:",
                    "app_data": ""
                },
                "4": {
                    "type": "html",
                    "value": "Glock-18 | Catacombs",
                    "color": "4b69ff",
                    "app_data": ""
                },
                "5": {
                    "type": "html",
                    "value": "M249 | System Lock",
                    "color": "4b69ff",
                    "app_data": ""
                },
                "6": {
                    "type": "html",
                    "value": "MP9 | Deadly Poison",
                    "color": "4b69ff",
                    "app_data": ""
                },
                "7": {
                    "type": "html",
                    "value": "SCAR-20 | Grotto",
                    "color": "4b69ff",
                    "app_data": ""
                },
                "8": {
                    "type": "html",
                    "value": "XM1014 | Quicksilver",
                    "color": "4b69ff",
                    "app_data": ""
                },
                "9": {
                    "type": "html",
                    "value": "Dual Berettas | Urban Shock",
                    "color": "8847ff",
                    "app_data": ""
                },
                "10": {
                    "type": "html",
                    "value": "Desert Eagle | Naga",
                    "color": "8847ff",
                    "app_data": ""
                },
                "11": {
                    "type": "html",
                    "value": "MAC-10 | Malachite",
                    "color": "8847ff",
                    "app_data": ""
                },
                "12": {
                    "type": "html",
                    "value": "Sawed-Off | Serenity",
                    "color": "8847ff",
                    "app_data": ""
                },
                "13": {
                    "type": "html",
                    "value": "AK-47 | Cartel",
                    "color": "d32ce6",
                    "app_data": ""
                },
                "14": {
                    "type": "html",
                    "value": "M4A4 | 龍王 (Dragon King)",
                    "color": "d32ce6",
                    "app_data": ""
                },
                "15": {
                    "type": "html",
                    "value": "P250 | Muertos",
                    "color": "d32ce6",
                    "app_data": ""
                },
                "16": {
                    "type": "html",
                    "value": "AWP | Man-o'-war",
                    "color": "eb4b4b",
                    "app_data": ""
                },
                "17": {
                    "type": "html",
                    "value": "Galil AR | Chatterbox",
                    "color": "eb4b4b",
                    "app_data": ""
                },
                "18": {
                    "type": "html",
                    "value": "or an Exceedingly Rare Special Item!",
                    "color": "ffd700",
                    "app_data": ""
                },
                "19": {
                    "type": "html",
                    "value": " ",
                    "app_data": ""
                },
                "20": {
                    "type": "html",
                    "value": "",
                    "color": "00a000",
                    "app_data": {
                        "limited": "1"
                    }
                }
            },
            "owner_descriptions": "",
            "tags": {
                "0": {
                    "internal_name": "CSGO_Type_WeaponCase",
                    "name": "Container",
                    "category": "Type",
                    "category_name": "Type"
                },
                "1": {
                    "internal_name": "set_community_6",
                    "name": "The Chroma Collection",
                    "category": "ItemSet",
                    "category_name": "Collection"
                },
                "2": {
                    "internal_name": "normal",
                    "name": "Normal",
                    "category": "Quality",
                    "category_name": "Category"
                },
                "3": {
                    "internal_name": "Rarity_Common",
                    "name": "Base Grade",
                    "category": "Rarity",
                    "color": "b0c3d9",
                    "category_name": "Quality"
                }
            },
            "classid": "720268538"
        },
        "success": true
    }
}

结果可以有多个返回我想知道结构应该是什么样的,这是我到目前为止所得到的但它没有返回。

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"`
}

type Tags struct {
    InternalName string `json:"internal_name"`
    Name         string `json:"name"`
    Category     string `json:"category"`
    Color        string `json:"color,omitempty"`
    CategoryName string `json:"category_name"`
}

如果有人能告诉我我的结构有什么问题,那将非常感谢。

令我困惑的是,Descriptions如何返回不是一个数组,而是多个对象,范围从0到20,当我不知道有多少对象要返回时,如何为此准备一个结构? result可以返回多个"720616831",那么它应该如何看待?

2 个答案:

答案 0 :(得分:2)

你会为第一个错误踢自己 - 你的JSON有result但你的struct标签有response

第二个问题是棘手的问题。问题是你声明你的Asset地图嵌套在结果中作为一个名为“资产”的键,但事实并非如此。实际上它只是结果其他的所有键而不是成功/错误。不幸的是,encoding/json无法表达这一点。您可以说resultmap[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
}

答案 1 :(得分:1)

我建议使用基类map[string]interface{}类型并从json字符串迭代,直到您可以构建整个结构。对于您不熟悉密钥的部分,例如0-20,地图可能就是您所拥有的。

例如,假设您的示例字符串在变量j中。你可以从:

开始
type AssetInfo struct {
    Result map[string]interface{}
}

并开始解编和打印以便找到完整的结构:

var ai AssetInfo
json.Unmarshal([]byte(j), &ai)
fmt.Printf("%#v\n", ai)

这将打印解编后构建的整个地图。尝试使用如此复杂的结构预先构建整个结构不太可能获得结果。

编辑:如果您将结果视为map[string]struct,就像使用Descriptions一样,则成功布尔会失败"并进入地图,但其余的json正确地解组。我没有看到支持Success布尔的方法以及结构其余部分的地图。至于数字键,如果你需要一个切片,你必须在解组后做一些工作。

type AssetInfo struct {
    Result map[string]Numbered
}

type Numbered struct {
    IconUrl          string                 `json:"icon_url"`
    IconUrlLarge     string                 `json:"icon_url_large"`
    IconDragUrl      string                 `json:"icon_drag_url"`
    Name             string                 `json:"name"`
    MarketHashName   string                 `json:"market_hash_name"`
    MarketName       string                 `json:"market_name"`
    NameColor        string                 `json:"name_color"`
    BGColor          string                 `json:"background_color"`
    Type             string                 `json:"type"`
    Tradable         string                 `json:"tradable"`
    Marketable       string                 `json:"marketable"`
    Commodity        string                 `json:"commodity"`
    TradeRestrict    string                 `json:"market_tradeable_restriction"`
    FraudWarnings    string                 `json:"fraudwarnings"`
    Descriptions     map[string]description `json:"descriptions"`
    OwnerDescription string                 `json:"owner_descriptions"`
    Tags             map[string]tag         `json:"tags"`
    ClassID          string                 `json:"classid"`
}

type description struct {
    Type    string `json:"type"`
    Value   string `json:"value"`
    Color   string `json:"color,omitempty"`
    AppData string `json:"appdata"`
}

type tag struct {
    InternalName string `json:"internal_name"`
    Name         string `json:"name"`
    Category     string `json:"category"`
    Color        string `json:"color,omitempty"`
    CategoryName string `json:"category_name"`
}

func main() {
    var ai AssetInfo
    json.Unmarshal([]byte(j), &ai)
    fmt.Printf("%+v\n", ai.Result["720268538"].Tags)
}

Tags的输出为map[0:{InternalName:CSGO_Type_WeaponCase Name:Container Category:Type Color: CategoryName:Type} 1:{InternalName:set_community_6 Name:The Chroma Collection Category:ItemSet Color: CategoryName:Collection} (...)

编辑2:在评论中讨论后,我最终得到了一些非常类似于hobbs'回答。他可能会更好地组织起来。

我们需要使用json.RawMessage,因为true的{​​{1}}值无法进入"success"结构。

Numbered