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

时间:2018-05-24 14:28:30

标签: c# post hubspot

我想向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" } ] }

我的代码生成“Key”和“Value”,而不是“property”和“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.'

2 个答案:

答案 0 :(得分:0)

C#的Json序列化程序不支持来自任何通用数据结构的属性的自定义命名...

尝试使用包含属性&#34; property&#34;的自定义类替换Dictionary。和&#34;价值&#34;代替。

答案 1 :(得分:0)

将HubspotContact更改为:

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

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