Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在MVCWebAPI中定制json结果_C#_Json_Asp.net Mvc_Asp.net Web Api_Jsonserializer - Fatal编程技术网

C# 如何在MVCWebAPI中定制json结果

C# 如何在MVCWebAPI中定制json结果,c#,json,asp.net-mvc,asp.net-web-api,jsonserializer,C#,Json,Asp.net Mvc,Asp.net Web Api,Jsonserializer,在我的Web Api应用程序中,我返回xml和json结果。格式在URL中指定。根据URL,我在Global.asax中指定了格式并返回结果。Global.asax是 protected void Application_Start() { GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add( new QueryStringMapping("format", "json

在我的Web Api应用程序中,我返回xml和json结果。格式在URL中指定。根据URL,我在Global.asax中指定了格式并返回结果。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;//for xml attribute
}
用于序列化的类是

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();
}
}
但我真的希望json像

[{"regions":[{"id":"AFRICA","name":"Africa"}]}]
我通过返回控制器中的内容

var regions = _continentService.GetAllContinents();
return Ok(regions);

有没有什么通用的方法来定制结果?我怎么能做到这一点呢?

这是不可能的,因为我知道你们有一系列地区。。目前我正在做的是。在控制器中,检查url是否包含格式,如果它是json`var regionsArray=new List();regionsArray.Add(regionsJson.Regions);返回Ok(regionsArray.ToArray());`这是好的还是有其他的解决方案?这是好的,因为你有数组…可能有这样的情况,你有更多的区域…在客户端,你可以解析响应,这将只给你一个重新排列的数组…所以在allok没有问题。唯一的问题是,所有的结果都有这个条件。代码变得更加冗长。代码冗余。。这就是为什么看看这个项目,它的已知问题
[{"regions":[{"id":"AFRICA","name":"Africa"}]}]
var regions = _continentService.GetAllContinents();
return Ok(regions);