[英]How to retrieve the values in a multi dimensional array using JSON?
我創建了一個多維數組..該數組存儲數據庫中的表行值。我需要將數組元素存儲為json格式,並且應單獨顯示數組元素(即,像在數據庫表中那樣明智地顯示)。 我的代碼在這里..但是它以json格式顯示所有數據,如下所示。 :
{"question":"6"}{"question":"mother?"}{"question":"fghh"}{"question":"bbb"}{"question":"qwe"}{"question":"wer"}{"question":"5"}{"question":"colg?"}{"question":"sdf"}{"question":"scf"}{"question":"aaa"}{"question":"dfdf"}
我的代碼在這里:
SqlDataAdapter da = new SqlDataAdapter("select question_num,q_text,answer1_text,answer2_text,answer3_text,answer4_text from question_bank_details where question_num in (select top 2 question_num from question_bank_details order by newid())", con5);
DataTable dt = new DataTable();
da.Fill(dt);
int i; int j;
string[,] array_questions = new string[dt.Rows.Count, dt.Columns.Count];
for (i = 0; i < dt.Rows.Count; i++)
{
for (j = 0; j < dt.Columns.Count; j++)
{
array_questions[i, j] = dt.Rows[i][j].ToString();
//Response.Write(array_questions[i, j]);
}
}
foreach (string question_row in array_questions)
{
var ques = new { question = question_row };
JavaScriptSerializer js = new JavaScriptSerializer();
// string json = js.Serialize(question_row);
string json = js.Serialize(ques);
Response.ContentType = "application/json";
Response.Write(json);
}
}
我如何像在數據庫表中那樣按行顯示它? 請幫忙 ? 我需要這樣的輸出:
{"question" : "6" "mother?" "bbb" "fghhh" "bbb" "qwe" "wer"}{"question" : "5" "colg" "sdf" "scf" "aaa" "ddd" "hjk"}
如果要使用具有命名屬性的對象的JSON數組,請嘗試以下操作:
var rows = dt.Rows
.Cast<DataRow>()
.Select(row => new {
ID = row[0],
Question = row[1],
Answer1 = row[2],
Answer2 = row[3],
Answer3 = row[4],
Answer4 = row[5],
})
.ToArray();
string json = js.Serialize(rows);
相反,如果您希望將數組作為JSON數組,請嘗試以下操作:
dt.Rows
.Cast<DataRow>()
.Select(row => new string[] {
row[0].ToString(),
row[1].ToString(),
row[2].ToString(),
row[3].ToString(),
row[4].ToString(),
row[5].ToString(),
})
.ToArray();
string json = js.Serialize(rows);
如果您還有其他需要,請相應地更新您的問題。
此鏈接可能會對您有所幫助。 它顯示了如何處理多維數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.