[英]Deserializing JSON throws TargetInvocationException
My data json format is: 我的数据json格式是:
[{"Email":"apatil.558@gmail.com","EmpCode":"10004","MobileNo":"","Name":"Sample Manager Eternus User","Pan":"MMMMM9876M","Photo":null,"message":{"Message":"Success"}}]
So I wrote this class to deserialize it to: 因此,我编写了此类,将其反序列化为:
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; }
}
I tried to read it using this code: 我尝试使用以下代码阅读它:
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;
}
Yet JsonConvert.DeserializeObject<EmpDetails>(e.Result)
throws an exception: 但是
JsonConvert.DeserializeObject<EmpDetails>(e.Result)
引发异常:
An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in System.Windows.ni.dll
System.Windows.ni.dll中发生了类型为'System.Reflection.TargetInvocationException'的未处理异常
Additional information: Exception has been thrown by the target of an invocation.
附加信息:调用的目标已引发异常。
How can I deserialize this JSON? 如何反序列化此JSON?
In the JSON string, the field "message" is not a string, it is an object. 在JSON字符串中,字段“ message”不是字符串,而是一个对象。 You must change the definition of EmpDetails to the following to get it work :
您必须将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; }
}
may be you have wrong class, it should be: 可能是您上错了课,应该是:
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; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.