I am working on asp.net webAPi, I have created a LoanInfo class which the values are set in a function and I finally put the LoanInfo in a list. I want to get all the values of the LoanInfo in Json but List always return empty values like [{},{}]. what am I missing. this is the loanInfo
我在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;
}
this is the method
这是方法
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();
}
}
thanks in advance!!
提前致谢!!
1 个解决方案
#1
2
The reason for that is you have private attributes, then when the serialization occurs, it can't read private values. Try to make properties on your DTO
instead private fields.
原因是你有私有属性,然后当序列化发生时,它无法读取私有值。尝试在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;
}
}
I've refactored your code, try this:
我重构了你的代码,试试这个:
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;
}
#1
2
The reason for that is you have private attributes, then when the serialization occurs, it can't read private values. Try to make properties on your DTO
instead private fields.
原因是你有私有属性,然后当序列化发生时,它无法读取私有值。尝试在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;
}
}
I've refactored your code, try this:
我重构了你的代码,试试这个:
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;
}