我有一个asp.net API,该API正在使用从服务器返回的xml数据。这是返回数据的格式(当我在地址栏中键入localhost ....时会得到什么)
ID = 3, fname = a, lname = a, phone = 123, company = abcID = 4, fname = a, lname = b, phone = c, company = dID = 5, fname = aa, lname = bb, phone = cc, company = ddID = 6, fname = Frame, lname = Blame, phone = 5555555555, company = Company
当我尝试使用C#从API返回数据时,出现此错误
将值“ ID = 3,fname = a,lname = a,电话= 123,公司= abc”转换为类型“ TestData”时出错
这是我用来尝试检索数据的方法。要正确返回数据该怎么办?
public List<TestData> GetGridInfo()
{
string URI = "http://localhost/api/getinfo";
using (var webClient = new System.Net.WebClient())
{
var json = webClient.DownloadString(URI);
var message = JsonConvert.DeserializeObject<List<TestData>>(json);
return message;
}
}
这是API语法->
public IEnumerable<string> Get()
{
List<string> result = new List<string>();
using (XamarinEntities entities = new XamarinEntities())
{
result = entities.appinfoes.AsEnumerable().Where(x => x.approveduser == null || x.approveduser=="No").Select(y => "ID = "+y.ID+", fname = "+ y.fname+", lname = "+ y.lname+", phone = "+ y.phone+", company = "+ y.company).ToList();
}
return result;
}
编辑->上面的语法是它在本地计算机上的外观,如果我使用服务器来访问本地主机,则这是我得到的格式,在我看来就像XML ...
<?xml version="1.0" encoding="ISO-8859-1"?>
<ArrayOfstring xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<string>ID = 3, fname = a, lname = a, phone = 123, company = abc</string>
<string>ID = 4, fname = a, lname = b, phone = c, company = d</string>
<string>ID = 5, fname = aa, lname = bb, phone = cc, company = dd</string>
</ArrayOfstring>
答案 0 :(得分:0)
您没有返回JSON。您返回的不是JSON的字符串数组
你应该做
public string Get()
{
List<string> result = new List<string>();
using (XamarinEntities entities = new XamarinEntities())
{
result = entities.appinfoes.AsEnumerable().Where(x => x.approveduser == null || x.approveduser=="No").Select(y => "ID = "+y.ID+", fname = "+ y.fname+", lname = "+ y.lname+", phone = "+ y.phone+", company = "+ y.company).ToList();
}
return JsonConvert.SerializeObject(result);
}
以上代码将返回JSON而不是字符串数组
更改代码以接收列表
例如
public List<string> GetGridInfo()
{
string URI = "http://localhost/api/getinfo";
using (var webClient = new System.Net.WebClient())
{
var json = webClient.DownloadString(URI);
var message = JsonConvert.DeserializeObject<List<string>>(json);
return message;
}
}
一条建议使用HttpClient代替WebClient