如何在浏览器或控制台中显示json?

时间:2015-10-08 09:24:56

标签: c#

我想知道如何在浏览器或控制台中显示json值?我目前的代码是否需要进行任何更改?

public class RootObject
{
    public string name { get; set; }
}

public static DataTable GetAlltheatredet()
{
    try
    {
        string connString = "Server=localhost;database=Mytable;uid=root;";
        string query = "SELECT Tnme FROM `Mytable`.`tdetails`";
        MySqlDataAdapter ma = new MySqlDataAdapter(query, connString);
        DataSet DS = new DataSet();
        ma.Fill(DS);
        return DS.Tables[0];  
    }
    catch (MySqlException e)
    {
        throw new Exception(e.Message);
    }
}

我的功能

[HttpGet]
public void jsonvalues()
{
    List<string> List = new List<string>();
    RootObject ro = new RootObject();
    DataTable dtaltheat = GetAlltheatredet();
    foreach (DataRow drow in dtaltheat.Rows)
    {
        string theatnme = drow["TheatreName"].ToString();
        ro.name = theatnme;
        JavaScriptSerializer js = new JavaScriptSerializer();
        var jsonString = JsonConvert.SerializeObject(ro);
        if(jsonString != null)
        { 
            List.Add(jsonString);
        }
    }
}

我正在使用datatable来获取我的表数据并创建一个根对象并将每个值添加到object并将该对象转换为json。

1 个答案:

答案 0 :(得分:0)

您必须从服务器发出return响应,才能在客户端接收。

[HttpGet]
public HttpResponseMessage jsonvalues()
{
    //your code

    //send response with status code 200 (OK)
    return Request.CreateResponse(HttpStatusCode.OK, List );
}

参考:http://www.codeproject.com/Articles/849034/Csharp-Web-API-HTTP-GET-with-a-Request-Body