如何在webAPi中获取Object到JSon的列表

时间:2016-05-18 12:59:52

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

我正在使用asp.net webAPi,我创建了一个LoanInfo类 哪个值在函数中设置,我最终将LoanInfo放在一个列表中。我想在Json中获取LoanInfo的所有值,但List总是返回空值,如[{},{}]。我错过了什么 这是loanInfo

public class LoanInfo
        {

             private String EmpID;
             private String amount;


            public LoanInfo(String EmpID,String amount)
            {


                this.EmpID = EmpID;
                this.amount = amount;

            }

这是方法

 public IEnumerable Get()
        {
            var con = new SqlConnection(sqlConStr);
            List<LoanInfo> loanInfo = new List<LoanInfo>();
            String query = "select EmpID,amount from employeeLoan";
            var cmd = new SqlCommand(query, con);

            try
            {
                con.Open();
                SqlDataReader read = cmd.ExecuteReader();
                while (read.Read())
                {
                    loanInfo.Add(new LoanInfo(read[0].ToString(), read[1].ToString()));
                }

                return loanInfo.ToList();
            }
            catch (Exception ex)
            {

                String a = ex.Message;
                return null;
            }
            finally
            {
                con.Close();
            }

        }

提前感谢!!

1 个答案:

答案 0 :(得分:2)

原因是你有私有属性,然后当序列化发生时,它无法读取私有值。尝试在DTO私有字段中创建属性。

public class LoanInfo
{    
     public string EmpID { get; set; }
     public string Amount { get; set; }

    public LoanInfo(string empID, String amount)
    {
        this.EmpID = EmpID;
        this.Amount = amount;
    }
}

我重构了你的代码,试试这个:

public IEnumerable<LoanInfo> Get()
{
    List<LoanInfo> loanInfo = new List<LoanInfo>();

    using (var con = new SqlConnection(sqlConStr))
    {
        try
        {
            con.Open();
            var cmd = new SqlCommand("select EmpID, amount from employeeLoan", con);
            SqlDataReader read = cmd.ExecuteReader();
            while (read.Read())
            {
                loanInfo.Add(new LoanInfo(read[0].ToString(), read[1].ToString()));
            }
        }
        catch (Exception ex)
        {
            return null;
        }
        finally
        {
            con.Close();
        }   
    }

    return loanInfo;
}