【问题标题】:How to Customize json? How can override WriteToStreamAsync method in the MediaTypeFormatter for the customization of json Result如何自定义json?如何覆盖 MediaTypeFormatter 中的 WriteToStreamAsync 方法以自定义 json 结果
【发布时间】:2015-05-31 08:37:06
【问题描述】:

我有一个 webApi 应用程序,它是从现有 Api 迁移而来的,因为客户端需要 json 和 xml 结果(在 URL http://localhost:1518/api/List?type=regions&format=json 中指定),所以在我的应用程序中,我有一个用于 xml 和 json 结果的类

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 结果都是这样。所以我尝试通过在 MediaTypeFormatter 类中创建一个 customJsonFormatter 类并覆盖 WriteToStreamAsync 方法来进行自定义,我不知道这是正确的方法,但我尝试了

 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;
    }
}

Global.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);
   }

在运行应用程序时,如果 URL 中的格式为 json,我会默认获取 xml 结果,并且也不会命中 customJsonFormatter 类中的 WriteToStreamAsync 方法。我怎样才能做到这一点?这是正确的方法吗?建议解决方案

【问题讨论】:

    标签: c# json asp.net-web-api jsonserializer mediatypeformatter


    【解决方案1】:

    对于 xml 案例,您可以使用 XmlElement 属性将 xml 格式化为添加 response_item 标记。与使用 Newtonsoft 类似(假设从序列化器语法),您可以使用 Json 特定属性。

    [JsonProperty("response_item")]
    [XmlElement("response_item")]
    public ContinentsList Regions { get; set; }
    

    在属性区域上。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-04
      • 2013-06-07
      • 2017-06-05
      • 1970-01-01
      • 1970-01-01
      • 2016-02-06
      • 2012-08-23
      • 1970-01-01
      相关资源
      最近更新 更多