У меня есть приложение WebApi, которое является переносом из существующего Api, поскольку клиенту нужен результат json и xml (который указан в URL-адресе http://localhost:1518/api/List?type=regions&format=json
), So In мое приложение у меня есть класс для XML и JSON результатКак настроить json? Как переопределить метод WriteToStreamAsync в MediaTypeFormatter для настройки json Result
public class ContinentData
{
[JsonProperty(PropertyName = "id")]
[XmlElement(ElementName = "id")]
public string Id { get; set; }
[XmlElement(ElementName = "name")]
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
}
[XmlRoot("response_item")]
public class ContinentsList
{
[XmlArray("regions")]
[XmlArrayItem("region")]
[JsonProperty(PropertyName = "regions")]
public List<ContinentData> Region { get; set; }
public ContinentsList()
{
Region = new List<ContinentData>();
}
}
[XmlRoot("response")]
public class Continents
{
[XmlElement("response_item")]
public ContinentsList Regions { get; set; }
public Continents()
{
Regions = new ContinentsList();
}
}
и я получаю вывод XML,
<response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<response_item>
<regions>
<region>
<id>AFRICA</id>
<name>Africa</name>
</region>
</response_item>
</response>
это хорошо, но в результате я получаю JSon
{"Regions":{"regions":[{"id":"AFRICA","name":"Africa"}]}}
Но я действительно хочу [{"regions":[{"id":"AFRICA","name":"Africa"}]}]
Я думаю, что для результатов json есть один класс. Все мой результат JSon, как that.So я пытаюсь настроить, создав класс customJsonFormatter и метод переопределяет WriteToStreamAsync в классе MediaTypeFormatter, я не знаю, что это правильный метод, но я стараюсь
public class CustomJsonFormatter : MediaTypeFormatter
{
public CustomJsonFormatter()
{
SupportedMediaTypes.Add(
new MediaTypeHeaderValue("application/json"));
SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/json"));
}
public override bool CanReadType(Type type)
{
if (type == (Type)null)
throw new ArgumentNullException("type");
return true;
}
public override bool CanWriteType(Type type)
{
return true;
}
public override Task WriteToStreamAsync(Type type, object value,
Stream writeStream, System.Net.Http.HttpContent content,
System.Net.TransportContext transportContext)
{
var task = Task.Factory.StartNew(() =>
{
// logic here
var json = JsonConvert.SerializeObject(value);
byte[] buf = System.Text.Encoding.Default.GetBytes(json);
writeStream.Write(buf, 0, buf.Length);
writeStream.Flush();
});
return task;
}
}
глобального. asax файл
protected void Application_Start()
{
GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(
new QueryStringMapping("format", "json", new MediaTypeHeaderValue("application/json")));
GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(
new QueryStringMapping("format", "xml", new MediaTypeHeaderValue("application/xml")));
GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true;
GlobalConfiguration.Configuration.Formatters.Add(new CustomJsonFormatter());
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.JsonFormatter);
}
Хотя запустить приложение и я получаю результат XML по умолчанию, если формат JSON в URL, а также не ударил по методу WriteToStreamAsync в классе customJsonFormatter. Как я могу это сделать? Правильно ли это? Предложить решение для этого