如何从类对象中获取JSON字符串 [英] How do I get a JSON string out of a class object
本文介绍了如何从类对象中获取JSON字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经将静态从字符串更改为对象但没有成功。
输入mo,dy和yr存在。
我用一个字符串编写了一个工作类语句,包括:idd,datetime,col1,col2和col3。
如何获得一个类对象中的JSON字符串?
错误代码:
I have changed the static from string to object with no success.
The inputs mo, dy and yr exist.
I have written a working class statement using a string including: idd, datetime, col1, col2 and col3.
How do I get a JSON string out of a class object?
Error Code:
[object Object]
Default.aspx.cs
Default.aspx.cs
public static string GetDate(string mo, string dy, string yr)
{
List<dataclass> returndata = new List<dataclass>();
dataclass dc = new dataclass();
var json = "";
string date1 = mo.ToString() + "/" + dy.ToString() + "/" + yr.ToString() + " 8:00 AM";
if (date1.Length > 6)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
string connStr = ConfigurationManager.ConnectionStrings["jsonobject"].ConnectionString;
string cmdStr = "SELECT * FROM [jsondata] WHERE [datetime1]=@datetime1;";
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand(cmdStr, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("@datetime1", date1);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(ds);
dt = ds.Tables[0];
foreach (DataRow dr in dt.Rows)
{
dc.idd = dr["idd"].ToString();
dc.datetime = dr["datetime1"].ToString();
dc.col1 = dr["col1"].ToString();
dc.col2 = dr["col2"].ToString();
dc.col3 = dr["col3"].ToString();
returndata.Add(dc);
}
}
}
}
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
json = serializer.Serialize(returndata);
}
else
{
json = "mo,dy,yr were null";
}
return json;
}
推荐答案
将Json.NET添加到您的项目中(使用NuGet),然后开始阅读: http://james.newtonking.com/json/help/index.html [ ^ ]
Add Json.NET to your project (use NuGet), then start reading here: http://james.newtonking.com/json/help/index.html[^]
这篇关于如何从类对象中获取JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文