如何修复序列化以生成正确的JSON [英] How do I fix my Serialization to produce correct JSON

查看:86
本文介绍了如何修复序列化以生成正确的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有错误,但[WebMethod]正在返回所有Nulls。这意味着我的序列化不对。



我的目标是产生一个返回json2:

I am getting no errors but the [WebMethod] is returning all "Nulls". This means my Serialization is not right.

My goal is to produce a return json2:

Json2 = {ID:someID, datetime:somedatetime, col1:somecol1, col2:somecol2, col3:somecol3};



这是我的代码:


Here is my code:

[System.Web.Services.WebMethod]
public static string GetJSONdata(string ID)
{
    DataSet ds = new DataSet();
    DataTable dt = new DataTable();
    string connStr = ConfigurationManager.ConnectionStrings["jsonobject"].ConnectionString;
    string cmdStr = "SELECT ([idd],[datetime],[col1],[col2],[col3]) FROM [jsondata] WHERE [idd]=@idd;";
    try
    {
        using (SqlConnection conn = new SqlConnection(connStr))
        {
            using (SqlCommand cmd = new SqlCommand(cmdStr, conn))
            {
                conn.Open();
                cmd.Parameters.AddWithValue("@idd", ID);
                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    da.Fill(ds);
                    dt = ds.Tables[0];
                }
            }
        }
    }
    catch (Exception ex)
    {

    }
    System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
    Dictionary<string, object> row;
    foreach (DataRow dr in dt.Rows)
    {
        row = new Dictionary<string, object>();
        foreach (DataColumn col in dt.Columns)
        {
            row.Add(col.ColumnName, dr[col]);
        }
        rows.Add(row);
    }
    var json2 = serializer.Serialize(rows);
    return json2;
}

推荐答案

因为你吞咽异常,你不能说问题是序列化。我用虚拟数据表测试了你的代码,并成功返回了json字符串。

删除try catch块或调试Web服务方法并检查收到的错误,然后只有你能正确识别问题,但遗憾的是我们无法调试你的代码。
since you are swallowing exception you can't say the issue is on serialization. I have tested you code with dummy data table and it was successfully returned json string.
Remove the try catch block or debug the web service method and check the error you received, then only you can identify the issue correctly but unfortunately we can't debug your code.


这篇关于如何修复序列化以生成正确的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆