json 字符串不适合我使用 Xamarin 制作的课程
Posted
技术标签:
【中文标题】json 字符串不适合我使用 Xamarin 制作的课程【英文标题】:json string do not fit in my made class using Xamarin 【发布时间】:2019-01-30 03:43:28 【问题描述】:我在一个项目的中间,我只是卡住了。我的问题是将 Json 字符串解析到我的班级。这是我的 Json:
"ReturnCode": 0,
"CampaignId": 155087586,
"TotalSMSSent": 1,
"TotalSMSwithError": 0,
"MSISDNwithErrorList":
这是我的课
public class RootObject
public int ReturnCode get; set;
public int CampaignId get; set;
public int TotalSMSSent get; set;
public int TotalSMSwithError get; set;
public List<MSISDNwithErrorList> MSISDNwithErrorList get; set;
public class MSISDNwithErrorList
这是我获取 json 字符串的代码
HttpClient client = new HttpClient();
var response = client.GetAsync("http://evolus.ddns.net/Q4Evolution/php/phpCategoria/BOPesquisaEmp.php").Result;
if (response.IsSuccessStatusCode)
string output = JsonConvert.SerializeObject(response.Content.ReadAsStringAsync().Result);
JsonConvert.DeserializeObject<RootObject>(output);
错误是这样的......
Newtonsoft.Json.JsonSerializationException: 将值“"ReturnCode":0,"CampaignId":155087586,"TotalSMSSent":1,"TotalSMSwithError":0,"MSISDNwithErrorList":" 转换为类型“AppTeste”时出错.RootObject'。路径 '',第 1 行,位置 115。
【问题讨论】:
你为什么要序列化你的 web 服务返回的 json?然后立即反序列化它?这没有任何意义? 【参考方案1】:MSISDNwithErrorList 成员似乎只是 json 结构中的对象
public class RootObject
public int ReturnCode get; set;
public int CampaignId get; set;
public int TotalSMSSent get; set;
public int TotalSMSwithError get; set;
//Change from List to Object
public MSISDNwithErrorList MSISDNwithErrorList get; set;
代码的其余部分应该像 ...
HttpClient client = new HttpClient();
var response =client.GetAsync("http://evolus.ddns.net/Q4Evolution/php/phpCategoria/BOPesquisa
Emp.php").Result;
if (response.IsSuccessStatusCode)
//Here Result already gives you a valid json, you do not need to serialize again
string output =response.Content.ReadAsStringAsync().Result;
//obj is your desired c# object
var obj =JsonConvert.DeserializeObject<RootObject>(output);
您可以在https://dotnetfiddle.net/CeXDNA 上查看您的工作代码
【讨论】:
我已经尝试了这两种方法,我将更改为对象但错误仍然相同 @Tiagodias 我编辑我的答案!! @Tiagodias 欢迎您,如果这解决了您的问题,请接受此作为答案!以上是关于json 字符串不适合我使用 Xamarin 制作的课程的主要内容,如果未能解决你的问题,请参考以下文章
如何从 Xamarin.forms pcl 中的 Url 检索 json 字符串
如何从 Xamarin.forms pcl 中的 Url 检索 json 字符串