【问题标题】:Formatting Json格式化 Json
【发布时间】:2014-04-01 10:36:22
【问题描述】:

我正在使用 Newtonsoft.Json

为此,我有以下代码,

    [WebMethod]
public static string GetData()
{
    string msg = string.Empty;
    string json;

    using (MySqlConnection con = new MySqlConnection("Server=localhost;Database=working_sample;uid=root;pwd=Tetra@123;pooling=false;"))
    {
        using (MySqlCommand cmd = new MySqlCommand("select * from json_example_table where subject='Swe'", con))
        {
            con.Open();
            cmd.ExecuteScalar();
            MySqlDataAdapter da = new MySqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);

            json = JsonConvert.SerializeObject(ds.Tables[0]); 
            // Using this I am getting single letter as output 
             // IN ASPX Code is as below.....
             success: function (data) {
                var objdata = $.parseJSON(data.d);
                var obj = data.d;
                 $('#txtname').val(obj[0]); // This is giving "[" as output


     //var settings = new JsonSerializerSettings { Formatting = Formatting.Indented };
     //string jsonn = JsonConvert.SerializeObject(ds, Formatting.None, settings);
        con.Close();
        }
    }

    return json;
}

我现在该怎么做才能获得正确的输出... 我已经尝试过格式化,但它给出的错误是

错误

  ambiguous ref btwn System.Xml.Formatting and System.Json.Formatting

请帮忙

【问题讨论】:

    标签: jquery json formatting


    【解决方案1】:

    当您使用Newtonsoft.Json 时,请使用正确的命名空间。 Formatting 属于 Newtonsoft.Json 命名空间,参考 Documentation

    尝试指定命名空间,如Newtonsoft.Json.Formatting

     using Newtonsoft.Json;
    
     .....
     .....
     .....
     var settings = new JsonSerializerSettings 
                      { Formatting = Newtonsoft.Json.Formatting.Indented };
    

    【讨论】:

    • 但是系统中不存在命名空间名称Json..,这是错误
    • Newtonsoft.Json.Formatting.JsonSerializerSettings 不包含格式化定义
    • @Pink,JsonSerializerSettings 属于Newtonsoft.Json 命名空间,而不是Newtonsoft.Json.Formatting。请看清楚我的回答
    • 仍然是同样的错误.. Newtonsoft.Json.JsonSerializerSettings 不包含我使用的格式定义与您给出的相同
    • 应该这样做,在文档中:james.newtonking.com/json/help/index.html?topic=html/… - 您可能需要检查您使用的是最新版本的 Newtonsoft.JSON。
    猜你喜欢
    • 2014-02-05
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-18
    • 2014-01-21
    • 2016-05-03
    • 1970-01-01
    相关资源
    最近更新 更多