C#嵌套对象序列化为JSON时抛出Bad Request错误问题咨询
Let’s walk through the most common reasons you might be hitting a Bad Request error when serializing your survey object, and how to fix them:
1. Mismatched Property Naming
Chances are, the API you’re sending the JSON to expects a specific casing (like PascalCase) but your C# class uses camelCase for property names. Newtonsoft.Json serializes properties using their exact C# names by default, which can cause the API to reject the request if it’s looking for differently named fields.
Fix: Use the [JsonProperty] attribute to explicitly map your C# properties to the names the API expects, or configure global serialization settings to enforce consistent casing:
Option 1: Attribute Mapping
public class survey { [JsonProperty("Title")] public string title { get; set; } [JsonProperty("Description")] public string description { get; set; } [JsonProperty("DeploymentType")] public string deploymentType { get; set; } [JsonProperty("DeploymentMethod")] public string deploymentMethod { get; set; } [JsonProperty("InstanceId")] public string instanceId { get; set; } [JsonProperty("What")] public surveyWhat what { get; set; } [JsonProperty("Contacts")] public string[] contacts { get; set; } } public class surveyWhat { [JsonProperty("RemoveDuplicates")] public bool removeDuplicates { get; set; } [JsonProperty("InstanceId")] public string instanceId { get; set; } [JsonProperty("Subject")] public string subject { get; set; } }
Option 2: Global Serialization Settings
var serializerSettings = new JsonSerializerSettings { // Use this if the API expects camelCase ContractResolver = new CamelCasePropertyNamesContractResolver(), // Or keep default PascalCase if that's what the API needs // ContractResolver = new DefaultContractResolver(), NullValueHandling = NullValueHandling.Ignore, // Skip null fields if API disallows them Formatting = Formatting.Indented }; string serializedJson = JsonConvert.SerializeObject(yourSurveyInstance, serializerSettings);
2. Missing Required Fields
Bad Requests often happen when the API expects certain fields to be present, but your serialized JSON is missing them (because the corresponding C# property is null or empty).
Fix:
- Check the API’s documentation to identify all required fields.
- Ensure those fields are populated with valid values in your
surveyandsurveyWhatobjects before serialization. - If the API allows optional fields to be omitted, use
NullValueHandling.Ignore(as shown above) to exclude null properties from the JSON.
3. Invalid Array or Nested Object Format
- The
contactsarray might be empty when the API expects at least one entry, or the entries don’t match the required format (e.g., invalid email addresses). - The
surveyWhatnested object could benullif the API requires it to be present even with default values.
Fix:
- Initialize
contactswith at least one valid entry if required:yourSurveyInstance.contacts = new string[] { "valid-email@example.com" }; - Ensure
surveyWhatis nevernull—initialize it with default values if needed:yourSurveyInstance.what = new surveyWhat { removeDuplicates = false, subject = "Default Subject" };
4. Boolean Serialization Mismatch
Some APIs expect boolean values to be sent as strings ("true"/"false") instead of JSON’s native boolean type (true/false). Newtonsoft.Json serializes C# bool values to the native JSON boolean by default, which might trigger a rejection.
Fix: Use a custom converter to serialize booleans as strings:
public class BooleanToStringConverter : JsonConverter<bool> { public override bool ReadJson(JsonReader reader, Type objectType, bool existingValue, bool hasExistingValue, JsonSerializer serializer) { return bool.Parse(reader.Value.ToString()); } public override void WriteJson(JsonWriter writer, bool value, JsonSerializer serializer) { writer.WriteValue(value ? "true" : "false"); } } // Apply to your property public class surveyWhat { [JsonProperty("RemoveDuplicates")] [JsonConverter(typeof(BooleanToStringConverter))] public bool removeDuplicates { get; set; } // ... other properties }
Critical Debug Step
Before anything else, print out the serialized JSON string and compare it directly against the API’s request schema. This will immediately show you if there are missing fields, naming mismatches, or invalid formats. You should also check the response body of the Bad Request—many APIs include detailed error messages that tell you exactly which field is causing the issue.
内容的提问来源于stack exchange,提问作者Jarrod Gassner

