【问题标题】:Convert Data table to nested json - webAPI将数据表转换为嵌套的 json - webAPI
【发布时间】:2020-05-07 09:57:15
【问题描述】:

我必须加入两个表并以 json 格式传递它的值。 我已经完成了如下操作

    public DataTable LoadDetails()
    {
        SqlConnection con = new SqlConnection(conn);
        string sql = "SELECT table_header.userid,table_header.name,table_details.Question_no,table_details.Question from table_header INNER JOIN table_details ON table_header.userid =table_details.useridWHERE table_header.active=@active";
        SqlCommand cmd = new SqlCommand(sql, con);
        con.Open();
        try
        {
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.AddWithValue("@active", 1);
            SqlDataReader dr = cmd.ExecuteReader();
            DataTable dt = null;

            if (dr.HasRows)
            {
                dt = new DataTable();
                dt.Load(dr);
            }
            else
            {
                dt = new DataTable();
                dt.Columns.Add("Status", typeof(string));
                dt.Rows.Add("fail");
            }

            return dt;
        }
        catch (Exception show_error)
        {
            throw show_error;
        }
        finally
        {
            cmd.Dispose();
            con.Close();
            con.Dispose();
        }
    }

在 web api 控制器中

 [Route("LoadDetails"), HttpGet]
    public HttpResponseMessage LoadDetails()
    {
        try
        {
            var Response = objLogic.LoadDetails();
            var Result = this.Request.CreateResponse(HttpStatusCode.OK, Response, new JsonMediaTypeFormatter());
            return Result;
        }
        catch (Exception ex)
        {
            HttpError Error = new HttpError(ex.Message) { { "IsSuccess", false } };
            return this.Request.CreateErrorResponse(HttpStatusCode.OK, Error);
        }
    }

现在我得到了如下回复,

[{"userid":42,"name":"Saran","Question_no":1,"Question":"xxxx?"},{"userid":42,"name":"Saran","Question_no":2,"Question":"yyyyy?"},{"userid":42,"name":"Saran","Question_no":3,"Question":"zzzz?"}]

由于这些用户标识和名称对所有行都是通用的,我怎样才能使其在 json 字符串中通用?

【问题讨论】:

    标签: c# asp.net json asp.net-web-api


    【解决方案1】:

    您需要的是Normalized JSON。

    第 1 步 - 创建一个符合规范化 json 要求的模型

    public class Normalized
    {
        public int userid { get; set; }
        public string name { get; set; }
    
        public List<NormalizedQuestion> questions { get; set; }
    }
    
    public class NormalizedQuestion
    {
        public int Question_no { get; set; }
        public string Question { get; set; }
    }
    

    第 2 步 - 遍历非规范化数据并转换为 JSON

    var normalized = new Normalized();
    var normalizedQuestions = new List<NormalizedQuestion>();
    foreach (var record in deNormalizedData)
    {
        normalized.userid = record.userid;
        normalized.name = record.name;
        normalizedQuestions.Add(new NormalizedQuestion() { Question = record.Question, Question_no = record.Question_no });                    
    }
    normalized.questions = normalizedQuestions;
    Console.WriteLine(JsonConvert.SerializeObject(normalized));
    

    这是输出

    {
        "userid": 42,
        "name": "Saran",
        "questions": [
            {
                "Question_no": 1,
                "Question": "xxxx?"
            },
            {
                "Question_no": 2,
                "Question": "yyyyy?"
            },
            {
                "Question_no": 3,
                "Question": "zzzz?"
            }
        ]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-08
      • 2022-01-07
      • 1970-01-01
      • 1970-01-01
      • 2021-12-17
      • 2017-03-21
      • 2020-12-16
      相关资源
      最近更新 更多