【问题标题】:Returning json result separated by new line返回由新行分隔的 json 结果
【发布时间】:2015-11-06 09:04:13
【问题描述】:

您好,我正在使用 asp.net web api 应用程序创建 web 服务,我正在以 json 格式返回结果,看起来像

[{"Name":"xxxxx","Age":"10"},{"Name":"yyyy","Age":"20"},{"Name":"zzzzz","Age":"30"}]

但我想要像

这样的输出
{"Name":"xxxxx","Age":"10"}
{"Name":"yyyy","Age":"20"}
{"Name":"zzzzz","Age":"30"}

谁能告诉我如何做到这一点?

编辑

这是我的代码

 public class Example
    {

        List<ResultData> resultdata = new List<ResultData>();

        public List<ResultData> Records(String value)
        {

            SqlCommand command = new SqlCommand("Select * from tablename where column=" +value + " LIMIT 1000");

            SqlDataReader reader = command.ExecuteReader();
            reader.FetchSize = int.MaxValue;

            SqlResultSet result = reader.FetchResult();


            foreach (SqlRecord row in result)
            {

                resultdata.Add(new ResultData() { Name = row[0].ToString(),Age = row[1].ToString() });


            }

            return resultdata;

        }

}

我的 webapiconfig.cs 看起来像这样

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            config.Formatters.JsonFormatter.
           SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
        }
    }
}

我也尝试返回一个类似 json 字符串的字符串,但它失败了,我已经转义了双引号,但结果中返回了带有转义符号的引号

【问题讨论】:

  • 第一个是对象数组,第二个是三个不同的对象。您可以发布执行此操作的代码,以便读者可以更好地指导您吗?此外,是显示输出的回报还是变量的回报?提供更多信息。

标签: asp.net json web-services asp.net-web-api


【解决方案1】:

问题是,为什么要这样做?你得到一个对象数组,但你想在一个响应中返回 3 个对象(根节点),这是不可能的。

也许these 指南有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-21
    • 1970-01-01
    • 1970-01-01
    • 2019-07-13
    • 2013-05-26
    • 1970-01-01
    • 2015-05-21
    相关资源
    最近更新 更多