如何修改C#代码生成符合HubSpot API要求的JSON格式?
解决HubSpot API请求JSON格式不匹配的400错误
我明白你现在遇到的问题——代码生成的JSON用了Key和Value字段,但HubSpot API要求的是property和value,导致返回400 Bad Request。下面给你两种可行的修改方案,你可以根据自己的习惯选择:
方案一:用自定义实体类替代Dictionary(推荐,更直观)
这种方式最直接,完全按照HubSpot要求的JSON结构来定义C#类,避免序列化时的字段名问题:
定义实体类
public class HubspotProperty { public string property { get; set; } public string value { get; set; } } public class HubspotContact { public List<HubspotProperty> properties { get; set; } }
修改JSON生成代码
// 创建联系人对象并添加属性 HubspotContact foo = new HubspotContact(); foo.properties = new List<HubspotProperty>(); foo.properties.Add(new HubspotProperty { property = "email", value = "alphatest@baconcompany.com" }); foo.properties.Add(new HubspotProperty { property = "firstname", value = "firstname" }); // 直接序列化,不需要自定义ContractResolver JsonSerializerSettings settings = new JsonSerializerSettings(); settings.Formatting = Formatting.Indented; string json = JsonConvert.SerializeObject(foo, settings);
这样生成的JSON就完全符合HubSpot的要求了:
{ "properties": [ { "property": "email", "value": "alphatest@baconcompany.com" }, { "property": "firstname", "value": "firstname" } ] }
方案二:修改自定义转换器,适配字段名
如果你想继续使用Dictionary,可以替换原来的DictionaryAsArrayResolver,让它把字典的键值对序列化成property和value:
自定义字典转属性数组的转换器
public class DictionaryToPropertiesConverter : JsonConverter { public override bool CanConvert(Type objectType) { return typeof(IDictionary<string, string>).IsAssignableFrom(objectType); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var dict = (IDictionary<string, string>)value; writer.WriteStartArray(); foreach (var kvp in dict) { writer.WriteStartObject(); writer.WritePropertyName("property"); writer.WriteValue(kvp.Key); writer.WritePropertyName("value"); writer.WriteValue(kvp.Value); writer.WriteEndObject(); } writer.WriteEndArray(); } // 如果不需要反序列化HubSpot的响应,这个方法可以留空或抛出异常 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException("反序列化未实现,如需使用请自行补充"); } }
更新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; // 替换原来的ContractResolver为自定义转换器 settings.Converters.Add(new DictionaryToPropertiesConverter()); string json = JsonConvert.SerializeObject(foo, settings);
最后检查请求代码
你的请求发送代码不需要修改,只要生成的JSON格式正确,就能正常和HubSpot API交互了。
内容的提问来源于stack exchange,提问作者Mario Landa
相关产品推荐
相关产品推荐

