首页 > 解决方案 > 使用自定义属性名称对 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.'

标签: c#posthubspot

解决方案


将 HubspotContact 更改为:

class PropertyValue
{
    public string Property { get;set;}
    public string Value { get;set;}
}
class HubspotContact
{
    public List<PropertyValue> Properties {get;set;}
}

它应该序列化为适当的格式,并且不需要自定义序列化程序。


推荐阅读