使用 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> 接口。

您可以通过两种方式填充 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 字段,这意味着相应字段可以在给定时间包含不同的类型,但只能包含一个值。OneOf 字段类似于 C 中的联合类型。

.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 属性共享存储空间,因此一项分配可能会覆盖之前的分配,从而导致细微 bug。例如,

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);