使用自定义 属性 名称编码 JSON

Encode JSON with custom property names

我想向 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# 的 Json 序列化程序不支持自定义命名来自任何通用数据结构的属性...

尝试用包含属性 "property" 和 "value" 的自定义 class 替换字典。

将 HubspotContact 更改为:

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

它应该序列化为正确的格式,不需要自定义序列化器。