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

本文关键字:显示 json 控制台 浏览器 | 更新日期: 2023-09-27 18:16:32

我想知道如何在浏览器或控制台中显示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来获取我的表数据并创建一个根对象,并将每个值添加到对象并将对象转换为json。

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

您必须从服务器接收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