我正在尝试使用JSON,当时我正在使用PostMan返回响应 这个错误发生了 System.Collections.Generic.List`1 [System.String]“}
public ActionResult SendVFCode(string Phone_Number)
{
var jsonSerialiser = new JavaScriptSerializer();
string error = "";
var SearchData ="";
if (Phone_Number == null)
{
error = "Must enter your phone number";
}
else if ( (db.PhoneNumbers.Select(x =>x.Id).Count() < 0)
&& (db.Assistant.Select(x =>x.Id).Count()) < 0)
{
error = "There are no data or your account is not activated";
}
else
{
SearchData = db.PhoneNumbers.Include(x => x.Assistant)
.Where(x => x.PhoneNumber == Phone_Number
&& x.Assistant.IsActive == true).Select(xx =>xx.PhoneNumber).ToList().ToString();
}
json = new
{
err = error,
ResultSearchData = SearchData
};
return Content(jsonSerialiser.Serialize(json));
}
答案 0 :(得分:0)
SearchData
不是字符串。不要将其声明为字符串,也不要尝试将字符串推入其中。这是一个列表(可能是List<string>
类型,也可能是您的电话号码类型)。
var SearchData =""
应该是:
List<string> SearchData;
您的数据库调用应以.ToList()
结尾,而不是.ToList().ToString()
。
答案 1 :(得分:0)
请注意,ToList()
后跟ToString()
返回列表的标准名称,而不是列表内容,因此,您应使用List<string>
来保存结果字符串(列表也必须是先实例化,然后再在if
块内使用)。正确的设置应如下所示:
public ActionResult SendVFCode(string Phone_Number)
{
var jsonSerialiser = new JavaScriptSerializer();
string error = "";
var SearchData = new List<string>(); // instantiate list of strings
var phoneCount = db.PhoneNumbers.Select(x => x.Id).Count();
var assistantCount = db.Assistant.Select(x => x.Id).Count();
if (Phone_Number == null)
{
error = "Must enter your phone number";
}
else if (phoneCount < 0 && assistantCount < 0)
{
error = "There are no data or your account is not activated";
}
else
{
// assign list from query results
SearchData = db.PhoneNumbers.Include(x => x.Assistant)
.Where(x => x.PhoneNumber == Phone_Number && x.Assistant.IsActive == true)
.Select(xx => xx.PhoneNumber).ToList();
}
var json = new
{
err = error,
ResultSearchData = SearchData
};
return Content(jsonSerialiser.Serialize(json));
}