列表

时间:2017-08-19 21:47:50

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

我有一个RESTFul服务,它以JSON格式返回一个列表。 JSON格式如下所示:

{
"cantidad": 241,
"reply": "6F5HH",
"location": "15 Azua - IP",
"str": "36%",
"date_Sent": "7/14/2017 9:58:31 AM",
"cant": 14,
"vehiculo": "",
"lc": "356612023737986"
},
{
"cantidad": 241,
"reply": "6F5HH",
"location": "15 Azua - IP",
"str": "36%",
"date_Sent": "7/20/2017 11:46:10 AM",
"cant": 1,
"vehiculo": "",
"lc": "356612023737986"
},
{
"cantidad": 241,
"reply": "5UG71",
"location": "AES NO REGISTRADO",
"str": "36%",
"date_Sent": "8/1/2017 1:35:29 PM",
"cant": 16,
"vehiculo": "",
"lc": "357042063498597"
},
{
"cantidad": 241,
"reply": "9LKYH",
"location": "AES NO REGISTRADO",
"str": "52%",
"date_Sent": "8/1/2017 1:38:09 PM",
"cant": 13,
"vehiculo": "",
"lc": "357042063498597"
},
{
"cantidad": 241,
"reply": "A3MA1",
"location": "AES NO REGISTRADO",
"str": "32%",
"date_Sent": "8/1/2017 1:38:09 PM",
"cant": 22,
"vehiculo": "",
"lc": "357042063498597"
}

如您所见,这是一个5项列表。我需要做的是生成JSON而不用逗号分隔每个项目。所以输出必须是这样的:

{
"cantidad": 241,
"reply": "6F5HH",
"location": "15 Azua - IP",
"str": "36%",
"date_Sent": "7/14/2017 9:58:31 AM",
"cant": 14,
"vehiculo": "",
"lc": "356612023737986"
}
{
"cantidad": 241,
"reply": "6F5HH",
"location": "15 Azua - IP",
"str": "36%",
"date_Sent": "7/20/2017 11:46:10 AM",
"cant": 1,
"vehiculo": "",
"lc": "356612023737986"
}
{
"cantidad": 241,
"reply": "5UG71",
"location": "AES NO REGISTRADO",
"str": "36%",
"date_Sent": "8/1/2017 1:35:29 PM",
"cant": 16,
"vehiculo": "",
"lc": "357042063498597"
}
{
"cantidad": 241,
"reply": "9LKYH",
"location": "AES NO REGISTRADO",
"str": "52%",
"date_Sent": "8/1/2017 1:38:09 PM",
"cant": 13,
"vehiculo": "",
"lc": "357042063498597"
}
{
"cantidad": 241,
"reply": "A3MA1",
"location": "AES NO REGISTRADO",
"str": "32%",
"date_Sent": "8/1/2017 1:38:09 PM",
"cant": 22,
"vehiculo": "",
"lc": "357042063498597"
}

这是我的.NET WebApi应用程序的注册方法:

    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        config.Formatters.Remove(config.Formatters.XmlFormatter); //DEVOLVER SOLO JSON 
        config.Formatters.JsonFormatter.SerializerSettings.Formatting       = Formatting.Indented;                          
        config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); 
    }

1 个答案:

答案 0 :(得分:0)

我不确定为什么你需要打破你的JSON,但仍然。我会使用这个序列化程序(你需要引用System.Web.Extensions):

using System.Web.Script.Serialization;
...
string jsonStr = new JavaScriptSerializer().Serialize(obj);
string notJsonStr = jsonStr.Replace("},{", "}{");
return notJsonStr;

不要忘记将您期望的内容类型配置为“text \ plain”而不是“application \ json”,因为此结果字符串将不再是JSON。