客户端应用程序将json数组发送到我的.net应用程序。我正在使用名称值集合接收它。现在我想读取它的值并将其分配给SQL查询的IN
子句。
HttpContext context = HttpContext.Current;
NameValueCollection nvc = context.Request.Form;
string co_json = nvc["co_json"];
// jsArray : [{"roll_number":"11","mark":"68"},{"roll_number":"22","mark":"70"}]";
// I want to get the two roll numbers from above json and need to pass it to SQL
SqlDataAdapter da = new SqlDataAdapter("select * from student_details where roll_number IN ( ???) ", con);
DataTable dt = new DataTable();
da.Fill(dt);
答案 0 :(得分:0)
您可以使用Newtonsoft JSON.NET将json转换为自定义c#对象 你可以创建一个这样的类:
public class RollMark
{
public string roll_number {get;set;}
public string mark {get;set;}
}
现在你可以这样做:
HttpContext context = HttpContext.Current;
NameValueCollection nvc = context.Request.Form;
string co_json = nvc["co_json"];// jsArray : [{"roll_number":"11","mark":"68"},{"roll_number":"22","mark":"70"}]";
//collect all rollMarks in json to c# list
var rollMarks = Newtonsoft.Json.JsonConvert.DeserializeObject<List<RollMark>>(co_json );
您现在可以在查询中添加参数,如下所示:
//format your IN query
string[] paramArray = rollMarks.Select(x, i) => "@settings" + i).ToArray();
string query = string.Format("select * from student_details where roll_number IN ({0})", string.Join(",", paramArray));
SqlDataAdapter da = new SqlDataAdapter(query, con);
DataTable dt = new DataTable();
for (int i = 0; i < rollMarks.Count(); ++i)
{
da.SelectCommand.Parameters.AddWithValue("@settings", rollMarks[i].roll_number)
}
da.Fill(dt);
答案 1 :(得分:0)
首先,拆分你的json数组以找到每个数组项。接下来,创建一个具有项目的每个属性的类。最后将你的每个json项目反序列化到类中。