使用 Protobuf 類型

由於 Google Ads API 使用 Protobuf 做為預設酬載格式,因此請務必 ,瞭解使用 API 時的一些 Protobuf 慣例和類型。

選填欄位

Google Ads API 中的許多欄位都標示為 optional。這樣一來, 區分欄位含有空白值的情況 並未傳回欄位值。這些欄位的運作方式和 但這些欄位也提供其他清除欄位和 檢查是否已設定欄位。

舉例來說,Campaign 物件的 Name 欄位會標示為「非必要」。 因此,您可以使用下列方法處理這個欄位。

// Get the name.
string name = campaign.Name;

// Set the name.
campaign.Name = name;

// Check if the campaign object has the name field set.
bool hasName = campaign.HasName();

// Clear the name field. Use this method to exclude Name field from
// being sent to the server in a subsequent API call.
campaign.ClearName();

// Set the campaign to empty string value. This value will be
// sent to the server if you use this object in a subsequent API call.
campaign.Name = "";

// This will throw a runtime error. Use ClearName() instead.
campaign.Name = null;

重複類型

在 Google Ads API 中,欄位陣列會顯示為唯讀 RepeatedField

一個例子是廣告活動的「url_custom_parameters」欄位是重複欄位 在 .NET 中則以唯讀 RepeatedField<CustomParameter> 表示 用戶端程式庫

RepeatedField 會導入 IList<T> 存取 API

填入 RepeatedField 欄位的方法有兩種。

舊版 C# 版本:使用 AddRange 方法新增值

範例如下:

Campaign campaign = new Campaign()
{
    ResourceName = ResourceNames.Campaign(customerId, campaignId),
    Status = CampaignStatus.Paused,
};

// Add values to UrlCustomParameters using AddRange method.
campaign.UrlCustomParameters.AddRange(new CustomParameter[]
{
    new CustomParameter { Key = "season", Value = "christmas" },
    new CustomParameter { Key = "promocode", Value = "NY123" }
});

較新的 C# 版本:使用集合初始化語法

// Option 1: Initialize the field directly.
Campaign campaign = new Campaign()
{
    ResourceName = ResourceNames.Campaign(customerId, campaignId),
    Status = CampaignStatus.Paused,
    // Directly initialize the field.
    UrlCustomParameters =
    {
        new CustomParameter { Key = "season", Value = "christmas" },
        new CustomParameter { Key = "promocode", Value = "NY123" }
    }
};

// Option 2: Initialize using an intermediate variable.
CustomParameter[] parameters = new CustomParameter[]
{
    new CustomParameter { Key = "season", Value = "christmas" },
    new CustomParameter { Key = "promocode", Value = "NY123" }
}

Campaign campaign1 = new Campaign()
{
    ResourceName = ResourceNames.Campaign(customerId, campaignId),
    Status = CampaignStatus.Paused,
    // Initialize from an existing array.
    UrlCustomParameters = { parameters }
};

其中一種類型

Google Ads API 中有部分欄位標示為 OneOf 欄位,表示該欄位 則只能包含不同的類型,但一次僅限一個值。其中一個欄位是 與 C 中的 union 類型類似

.NET 程式庫為每個型別提供一個屬性,藉此實作 OneOf 欄位 OneOf 欄位中的保留值,且會更新 共用課程欄位

舉例來說,廣告活動的 campaign_bidding_strategy 標示為 OneOf ] 欄位。此類別實作方式如下 (為求簡潔,程式碼經過簡化):

public sealed partial class Campaign : pb::IMessage<Campaign>
{
    object campaignBiddingStrategy_ = null;
    CampaignBiddingStrategyOneofCase campaignBiddingStrategyCase_;

    public ManualCpc ManualCpc
    {
        get
        {
            return campaignBiddingStrategyCase_ == CampaignBiddingStrategyOneofCase.ManualCpc ?
                (ManualCpc) campaignBiddingStrategy_ : null;
        }
        set
        {
            campaignBiddingStrategy_ = value;
            campaignBiddingStrategyCase_ = CampaignBiddingStrategyOneofCase.ManualCpc;
        }
    }

    public ManualCpm ManualCpm
    {
        get
        {
            return campaignBiddingStrategyCase_ == CampaignBiddingStrategyOneofCase.ManualCpm ?
                (ManualCpm) campaignBiddingStrategy_ : null;
        }
        set
        {
            campaignBiddingStrategy_ = value;
            campaignBiddingStrategyCase_ = CampaignBiddingStrategyOneofCase.ManualCpm;
        }
    }

    public CampaignBiddingStrategyOneofCase CampaignBiddingStrategyCase
    {
        get { return campaignBiddingStrategyCase_; }
    }
}

由於 OneOf 屬性會共用儲存空間,因此一項指派可以覆寫先前 導致細微錯誤例如:

Campaign campaign = new Campaign()
{
    ManualCpc = new ManualCpc()
    {
        EnhancedCpcEnabled = true
    },
    ManualCpm = new ManualCpm()
    {

    }
};

在本例中,campaign.ManualCpc 現在是 null,因為初始化 campaign.ManualCpm 欄位會覆寫先前以下項目的初始化作業: campaign.ManualCpc

轉換為其他格式

您可以輕鬆將 protobuf 物件轉換為 JSON 格式,以及反向操作。這是 因此,在建構需要與其他系統互動的系統時 需要 JSON 或 XML 等文字型資料。

GoogleAdsRow row = new GoogleAdsRow()
{
    Campaign = new Campaign()
    {
        Id = 123,
        Name = "Campaign 1",
        ResourceName = ResourceNames.Campaign(1234567890, 123)
    }
};
// Serialize to JSON and back.
string json = JsonFormatter.Default.Format(row);
row = GoogleAdsRow.Parser.ParseJson(json);

您也可以將物件序列化為位元組,然後再進行序列化。二進位序列化作業更勝以往 高效率的記憶體和儲存空間 比 JSON 格式更有效

GoogleAdsRow row = new GoogleAdsRow()
{
    Campaign = new Campaign()
    {
        Id = 123,
        Name = "Campaign 1",
        ResourceName = ResourceNames.Campaign(1234567890, 123)
    }
};
// Serialize to bytes and back.
byte[] bytes = row.ToByteArray();
row = GoogleAdsRow.Parser.ParseFrom(bytes);