我有一个 asp.net 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,phone = 123,company = 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>
您没有返回 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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句