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# 从Web API中的通用列表返回Json_C#_Json_Serialization_Asp.net Web Api_Generic List - Fatal编程技术网

C# 从Web API中的通用列表返回Json

C# 从Web API中的通用列表返回Json,c#,json,serialization,asp.net-web-api,generic-list,C#,Json,Serialization,Asp.net Web Api,Generic List,我的列表如下所示: public static List<SearchFormula> SearchData(string searchString) { var searchResults = new List<SearchFormula>(); SqlDataReader drResults = FormulaUtility.SearchFormulas(searchString); if ((drResults != null) &

我的列表如下所示:

public static List<SearchFormula> SearchData(string searchString)
{
    var searchResults = new List<SearchFormula>();

    SqlDataReader drResults = FormulaUtility.SearchFormulas(searchString);

    if ((drResults != null) && (drResults.HasRows))
    {                
        while (drResults.Read())
        {
            searchResults.Add(new SearchFormula() 
            {  
                // id  use the GetValue function
                Title = drResults.GetString(1),
                Description = drResults.GetString(2), 
                Url = drResults.GetString(3)
                // total use the GetValue Function
                });
            }
        }
    return searchResults;
}
我开始使用IHttpActionResult,返回OK(结果);功能。我相信这就是让我开始迷茫的原因。我已经成功地发送了一个ArrayList,但这并没有像我想象的那样序列化

我尝试将其更改为ActionResult,并尝试返回Json(结果)结果作为实际列表

我想继续使用IhttpActionResult并使用OK()方法发送序列化数据。内置json序列化程序和NewtonSoft json序列化程序之间似乎也存在冲突

我应该用什么。序列化泛型列表并将结果传递到IHttpActionResult OK()方法的最简单方法是什么

我尝试了JavaScriptSerializer,但它返回的是XML而不是Json

public class SearchController : ApiController
{
    public IHttpActionResult Get(string searchTerm)
    {            
        var jsonSerialiser = new JavaScriptSerializer();
        var jsonResult = jsonSerialiser.Serialize(SearchUtility.SearchData(searchTerm));

        if (jsonResult != null)
        {
            return Ok(jsonResult);
        }
        return NotFound();

    }
}
以下是Json.Net示例:

public class SearchController : ApiController
{
    public IHttpActionResult Get(string searchTerm)
    {   
        var jsonResult = JsonConvert.SerializeObject(SearchUtility.SearchData(searchTerm));

        if (jsonResult != null)
        {
            return Ok(jsonResult);
        }
        return NotFound();        
    }
}
我试过记忆之流。。。废话废话。。。没有什么看起来像是一个干净、直接的方法,也没有这个特定解决方案的主题

让我从这个开始

如何将通用列表序列化为Json

我如何通过IHttpActionResult发送该结果

*更新*

这就是我从Json.Net获得的序列化。但是格式有点问题。。。即使是Fiddler也无法确定它是Json。我的标题看起来像这样(在Fiddler中):

接受:application/json,text/javascript,/;q=0.01

“[{”title\“:\”Lacidofil®“,”description\”:“Lacidofil®具有Rosell研究所的瑞士乳杆菌和鼠李糖乳杆菌。这两种菌株都已在人类临床试验中得到广泛研究,具有…\”,“url\”:“/产品/产品详细信息。aspx?pid=103\”,{”title\:“MedCaps GI™\“,\”描述\“:\”MedCaps GI™ 功能成分旨在从营养角度支持胃肠道衬里的完整性和最佳功能。添加营养素,如l-谷氨酰胺…\“,\“url\”:\“/products/product detail.aspx?pid=114\”,{“title\”:\“OrganiX™ 植物性食品™\“,”说明\“:\”有机质植物食品是一种方便的粉末状配方,提供关键营养素,以支持健康的生活方式。该综合配方融合了有机质的创新混合物…\”,\“url\”:\“/products/product detail.aspx?pid=271\”,{“title\”:“益生菌防御”™\“,”描述“:\”概率防御™ 是支持免疫系统的益生菌的最佳组合。\r\n此产品包含:\r\n\r\nHelveticus Rosell-52(30亿)\r\nActobacillu…\,\“url\”:\“/products/product detail.aspx?pid=102\”,{\“title\”:\“益生菌每日DF”™\“,”说明\“:\”益生菌每日DF™ 是一种素食、不含乳制品和麸质的四株益生菌,每粒胶囊总价值300亿CFU†。每粒素食胶囊都用氮气净化的alu…\,“url\”:\“/products/products detail.aspx?pid=181\”,{“title\”:“ProbioMax DF”密封™\“,\”说明\“:\”ProbioMax DF™ 是一种素食、不含奶制品和麸质的四种益生菌,每粒胶囊总计1000亿CFU†。每粒素食胶囊用氮气净化铝密封…\“,\“url\”:\“/products/products detail.aspx?pid=184\”,{“title\”:“ProbioMax Plus DF™\“,”描述\“:\”通过单独补充益生菌菌株、非致病性酵母、布拉氏酵母菌、免疫球蛋白等获得的多种健康益处,“,”url \“:\”/products/product detail.aspx?pid=185\”,“{”title \“:”酵母菌素DF™\“,”说明\“:\”酵母菌素DF™ 是一种不含乳糖、抗胃酸、稳定、正在申请欧洲专利的配方,含有经DNA验证的布拉迪酵母菌。这种益生菌酵母支持物…\”,“url\”:\“/products/product detail.aspx?pid=197\”)”


我通常使用以下扩展方法序列化为JSON:

    public static class Extensions
{
    public static string SerializeToJson<T>(this T obj, DateTimeSerializationFormat format = DateTimeSerializationFormat.DotNet) where T : class
    {
        string result;
        var serializer = new DataContractJsonSerializer(typeof(T));
        using (var stream = new MemoryStream())
        {
            serializer.WriteObject(stream, obj);
            result = Encoding.UTF8.GetString(stream.ToArray());
        }

        if (formaat != DateTimeSerializationFormat.DotNet)
        {
            const string dotNetDateTimePattern = @"""\\/Date\((-?\d+)([\+-]\d{4})?\)\\/""";

            if (format ==DateTimeSerializationFormat.Iso8601 || format ==DateTimeSerializationFormat.Ruby))
            {
                var matchEvaluator = new MatchEvaluator(ConvertJsonDateToIso8601DateString);
                var regex = new Regex(dotNetDateTimePattern);
                resultaat = regex.Replace(resultaat, matchEvaluator);
                if (format == DateTimeSerializationFormat.Ruby && resultaat.Length > 10) // Ruby time
                {
                    result = Regex.Replace(result, @"([\+-]\d{1,2}\:\d{2})", " $0"); // Add an space before the timeZone, for example bv "+01:00" becomes " +01:00"
                }
            }

        }
        return result;
    }

    public enum DateTimeSerializationFormat
    {
        /// <summary>
        /// Example: "\/Date(1198908717056)\/" (aantal miliseconden na 1-1-1970)
        /// </summary>
        DotNet,
        /// <summary>
        /// Example: "1997-07-16T19:20:30.45+01:00"
        /// </summary>
        Iso8601,
        /// <summary>
        /// Example: "1997-07-16T19:20:30.45 +01:00"
        /// </summary>
        Ruby,
        ///// <summary>
        ///// Example: new Date(1198908717056) or other formats like new (date (1997,7,16)
        ///// </summary>
        //JavascriptDateObject
    }

我采用这种方法,这种方法似乎简单得多,并且不涉及为您拥有的数据更改json序列化程序

如果以列表形式返回对象,则默认的媒体类型格式化程序将根据从客户端指定的内容类型(提供json或xml)处理序列化

出于演示目的,添加以下返回硬编码对象的方法

    // GET api/search
    public List<SearchFormula> Get(string searchTerm)
    {
        var searchItems = SearchData(searchTerm);
        return searchItems;
    }

    public static List<SearchFormula> SearchData(string searchString)
    {
        var searchResults = new List<SearchFormula>();

        searchResults.Add(new SearchFormula { Description = "desc1", Title = "title1", Url = "http://url.com" });
        searchResults.Add(new SearchFormula { Description = "desc2", Title = "title2", Url = "http://url.com" });

        return searchResults;

    }
//获取api/搜索
公共列表获取(字符串搜索术语)
{
var searchItems=搜索数据(搜索术语);
返回搜索项目;
}
公共静态列表SearchData(字符串searchString)
{
var searchResults=新列表();
添加(新的搜索公式{Description=“desc1”,Title=“title1”,Url=”http://url.com" });
添加(新的搜索公式{Description=“desc2”,Title=“title2”,Url=”http://url.com" });
返回搜索结果;
}
然后在fiddler中指定客户端接受
application/json
,如下图所示,内容返回为
json

有关序列化的更多信息,请参见此处:


您研究过Json.Net吗?这是问题的一部分,我发现默认值和newtonsoft之间存在冲突。我认为Web API默认情况下已经使用了Json.Net。在我写的东西中,我总是返回我的对象,除非我特别想返回HTTP错误代码。这样,如果您的客户希望使用XML而不是JSON,您就没有更多的工作要做了。根据您的更新,fiddler之所以不将其视为JSON,是因为它是JSON字符串,而不是JSON。请注意前导和尾随的双引号,以及整个过程中所有转义的引号。@DAMINCE88,谢谢。这和我看到的一样,也是我困惑的原因。为什么要序列化为一个字符串?如何转换为Json?(由于整个字符串,我的Ajax调用无法按id“解析”数据。)标头是正确的。对象已正确填充。更新我的问题中的结果。我突出显示了json res
System.Runtime.Serialization.Json;
    // GET api/search
    public List<SearchFormula> Get(string searchTerm)
    {
        var searchItems = SearchData(searchTerm);
        return searchItems;
    }

    public static List<SearchFormula> SearchData(string searchString)
    {
        var searchResults = new List<SearchFormula>();

        searchResults.Add(new SearchFormula { Description = "desc1", Title = "title1", Url = "http://url.com" });
        searchResults.Add(new SearchFormula { Description = "desc2", Title = "title2", Url = "http://url.com" });

        return searchResults;

    }