Reputation: 16502
I have a abstract class with an JsonConverter attribute like so:
[JsonConverter(typeof(SurveyItemConverter))]
public abstract class SurveyItem:ISurveyItem
{
private class SurveyItemConverter : JsonCreationConverter<ISurveyItem>
{
protected override ISurveyItem Create(Type objectType, Newtonsoft.Json.Linq.JObject jObject)
{
var type = (SurveyItemType)jObject.Value<int>("Type");
switch (type)
{
case SurveyItemType.Label:
return new SurveyLabel();
case SurveyItemType.Textbox:
return new SurveyTextbox();
case SurveyItemType.TextArea:
return new SurveyTextArea();
case SurveyItemType.CheckBoxGroup:
return new SurveyCheckboxGroup();
case SurveyItemType.Checkbox:
return new SurveyCheckbox();
case SurveyItemType.RadioGroup:
return new SurveyRadioGroup();
case SurveyItemType.RadioButton:
return new SurveyRadioButton();
case SurveyItemType.Email:
return new SurveyEmail();
case SurveyItemType.Telephone:
return new SurveyTelephone();
case SurveyItemType.Number:
return new SurveyNumber();
case SurveyItemType.DateTime:
return new SurveyDate();
case SurveyItemType.Password:
return new SurveyPassword();
case SurveyItemType.Url:
return new SurveyUrl();
case SurveyItemType.ProfileName:
return new SurveyProfileName();
default:
throw new ArgumentOutOfRangeException();
}
}
}
public string Label { get; set; }
public int Id { get; set; }
public SurveyItemType Type { get; set; }
}
This works fine if the request is a POST/PUT, but with a GET request it fails:
Cannot create an abstract class
The controller that handles the get request has a method with the signature (this method is for browsers that do not support CORS):
[HttpGet]
public async Task<IHttpActionResult> SubmitSurvey(HttpRequestMessage request, [FromUri] Survey survey)//survey contains a List<SurveyItem>
Why is it not using the JsonConverter? How can I get the JsonConverter to work with this method?
Upvotes: 1
Views: 1260
Reputation: 129667
Web API uses content type negotiation to determine what deserializer to use. A GET request has no body and thus no content type. Web API is not expecting to find JSON in the URL, so it does not use Json.Net in this case, and your converter does not get called. Obviously the best choice is to use POST, but if you have to get it to work with GET you will need to either:
Here is a similar question that might be of some help regarding the first two options.
Upvotes: 3