c# - 使用自定义属性名称对 JSON 进行编码
问题描述
我想向 Hubspot API ( https://developers.hubspot.com/docs/methods/contacts/create_or_update ) 发出 POST 请求,我需要 JSON 来匹配这种格式:
{ "properties": [ { "property": "firstname", "value": "HubSpot" } ] }
相反,我得到了这个:
{ "properties": [ { "Key": "email", "Value": "alphatest@baconcompany.com" }, { "Key": "firstname", "Value": "testfirstname" } ] }
我的代码不是 "property" 和 "value" ,而是生成 "Key" 和 "Value" ,如何更改我的 JSON 以匹配正确的格式?
这是我生成该字典的方式:
public class HubspotContact
{
public Dictionary<string, string> properties { get; set; }
}
private static readonly HttpClient client = new HttpClient();
class DictionaryAsArrayResolver : DefaultContractResolver
{
protected override JsonContract CreateContract(Type objectType)
{
if (objectType.GetInterfaces().Any(i => i == typeof(IDictionary) ||
(i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IDictionary<,>))))
{
return base.CreateArrayContract(objectType);
}
return base.CreateContract(objectType);
}
}
这就是我生成 JSON 的方式:
HubspotContact foo = new HubspotContact();
foo.properties = new Dictionary<string, string>();
foo.properties.Add("email", "alphatest@baconcompany.com");
foo.properties.Add("firstname", "firstname");
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.Formatting = Formatting.Indented;
settings.ContractResolver = new DictionaryAsArrayResolver();
string json = JsonConvert.SerializeObject(foo, settings);
最后这是我发送请求的方式:
var httpWebRequest =(HttpWebRequest)WebRequest.Create("https://api.hubapi.com/contacts/v1/contact/createOrUpdate/email/alphatest@baconcompany.com/?hapikey=myapikey");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())){
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Console.WriteLine(result.ToString());
}
现在我收到这个错误的请求:
System.Net.WebException: 'The remote server returned an error: (400) Bad Request.'
解决方案
将 HubspotContact 更改为:
class PropertyValue
{
public string Property { get;set;}
public string Value { get;set;}
}
class HubspotContact
{
public List<PropertyValue> Properties {get;set;}
}
它应该序列化为适当的格式,并且不需要自定义序列化程序。
推荐阅读
- c# - 尝试在 GDrive API v3 上创建评论时出错
- angular - 如何使用 forEach 向类似于 push(array) 的对象添加值
- android - Android UI automator:打开应用两次,测试交互
- c# - Assembly.LoadFrom 在 .NET Core 和 .NET Framework 中的工作方式不同
- javascript - Angular 6 + Routes Resolver = 生产中的 404 页
- c++ - 移动时使正方形变大
- lstm - 试图在 tensorflow 上设置种子以在 LSTM 上进行可复制的运行?
- azure-active-directory - 如何让 Azure 逻辑应用使用其托管服务标识通过连接器进行身份验证?
- python - 为 Pandas 数据框单元分配来自其他数据框元素的输入
- hammerspoon - 如何在 Hammerspoon 的监视器之间移动应用程序?