我的数据json格式是:
[{"Email":"apatil.558@gmail.com","EmpCode":"10004","MobileNo":"","Name":"Sample Manager Eternus User","Pan":"MMMMM9876M","Photo":null,"message":{"Message":"Success"}}]
所以我写了这个类来反序列化为:
public class EmpDetails
{
public string Email { get; set; }
public string EmpCode { get; set; }
public string MobileNo { get; set; }
public string Name { get; set; }
public string Pan { get; set; }
public string Photo { get; set; }
public string Message { get; set; }
}
我尝试使用此代码阅读它:
private void SihnIn_OnClick(object sender, RoutedEventArgs e)
{
string uri = "http://xyz.d.in/service1.svc/getUser/MMMMM9876M/10004";
WebClient webClient = new WebClient();
webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadStringCompleted);
webClient.DownloadStringAsync(new Uri(uri));
}
void DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
var jsonData = JsonConvert.DeserializeObject<EmpDetails>(e.Result); //Getting Error in this line
string getEmail = jsonData.Email;
}
然而JsonConvert.DeserializeObject<EmpDetails>(e.Result)
引发了异常:
System.Windows.ni.dll中发生未处理的“System.Reflection.TargetInvocationException”类型异常
附加信息:调用目标引发了异常。
如何反序列化此JSON?
答案 0 :(得分:2)
在JSON字符串中,字段&#34; message&#34;不是字符串,它是一个对象。 您必须将EmpDetails的定义更改为以下内容才能使其正常工作:
public class EmpDetails
{
public string Email { get; set; }
public string EmpCode { get; set; }
public string MobileNo { get; set; }
public string Name { get; set; }
public string Pan { get; set; }
public object Photo { get; set; }
public Message message { get; set; }
}
public class Message
{
public string message { get; set; }
}
答案 1 :(得分:1)
可能是你错了,应该是:
public class Message
{
public string Message { get; set; }
}
public class EmpDetails//changed name
{
public string Email { get; set; }
public string EmpCode { get; set; }
public string MobileNo { get; set; }
public string Name { get; set; }
public string Pan { get; set; }
public string Photo { get; set; }//changed type
public Message message { get; set; }
}