【问题标题】:How to retrieve the values in a multi dimensional array using JSON?如何使用 JSON 检索多维数组中的值?
【发布时间】:2013-06-05 05:05:03
【问题描述】:

我创建了一个多维数组..它存储数据库中的表行值..我需要将数组元素存储为 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"}

【问题讨论】:

    标签: c# asp.net json json.net


    【解决方案1】:

    如果您想要一个带有命名属性的 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);
    

    如果您想要其他内容,请相应地更新您的问题。

    【讨论】:

      【解决方案2】:

      Your serializing 将数据转换为JSON。您尝试做的不是 JSON。

      根据您提供的信息,您正在尝试做一些不标准的事情 - 您可能需要自己编写代码。

      【讨论】:

        猜你喜欢
        • 2016-12-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多