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 }
};
OneOf 유형
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 속성은 저장소를 공유하므로 한 할당이 이전 할당을 덮어쓸 수 있으며, 이로 인해 미묘한 버그가 발생할 수 있습니다. 예를 들면 다음과 같습니다.
Campaign campaign = new Campaign()
{
ManualCpc = new ManualCpc()
{
EnhancedCpcEnabled = true
},
ManualCpm = new ManualCpm()
{
}
};
이 경우 campaign.ManualCpm
필드를 초기화하면 campaign.ManualCpc
의 이전 초기화가 덮어쓰기되므로 campaign.ManualCpc
는 이제 null
입니다.
다른 형식으로 변환
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);