Web Api返回不希望的json格式

时间:2018-10-16 11:43:38

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

方法:

[Route("api/vms/getpowerstatus/{vmsid}")]
[HttpGet]
public string getpowerstatus(string vmsid)
{ 
    Result rs = new Result();
    try
    {
        DataSet ds = new DataSet();
        String timeStamp = GetTimestamp();

        string q = "select vmsid, vmspowerstatus ,vmspowerdatetime from public.vmssnapshot  ";
        ds = vm.GetVMS(q);
        rs.vmsid = vmsid;
        rs.status = "success";

        string json = JsonConvert.SerializeObject( ds.Tables[0] , Formatting.None);
        return json;
    }
    catch (Exception ex)
    {

    } 
}

回复:

"[{\"vmsid\":\"512\",\"vmspowerstatus\":null,\"vmspowerdatetime\":null},{\"vmsid\":\"VMSBhandup98\",\"vmspowerstatus\":null,\"vmspowerdatetime\":null},{\"vmsid\":\"tquwuer\",\"vmspowerstatus\":null,\"vmspowerdatetime\":null},{\"vmsid\":\"VMSBlock\",\"vmspowerstatus\":\"1\",\"vmspowerdatetime\":1539022768},{\"vmsid\":\"uu4443\",\"vmspowerstatus\":\"1\",\"vmspowerdatetime\":1534917021},{\"vmsid\":\"cms_bhandup\",\"vmspowerstatus\":\"1\",\"vmspowerdatetime\":1539022544},{\"vmsid\":\"vmsBolakk\",\"vmspowerstatus\":\"1\",\"vmspowerdatetime\":1539631400}]"

所需的响应:

[{vmsid:'512',vmspowerstatus:'test'.....}]

1 个答案:

答案 0 :(得分:0)

Asp.Net web api serialize your result in json,因此您无需序列化结果。只需返回对象或可枚举的对象进行序列化即可。

如果需要自定义序列化,则可以在Web api配置注册中配置序列化器

public static void Register(HttpConfiguration config)
{
    //Web API routes
    config.MapHttpAttributeRoutes();

    //configure serializer
    config.Formatters.JsonFormatter.SerializerSettings = new Newtonsoft.Json.JsonSerializerSettings();
    config.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
    config.Formatters.JsonFormatter.SerializerSettings.DateFormatString = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fff'Z'";
}