反序列化JSON会引发TargetInvocationException

本文关键字:TargetInvocationException JSON 反序列化 | 更新日期: 2023-09-27 18:00:53

我的数据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?

反序列化JSON会引发TargetInvocationException

在JSON字符串中,字段"message"不是字符串,而是对象。您必须将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; }
}

可能是您有错误的类,它应该是:

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; }
}

http://json2csharp.com/

相关文章:
  • 没有找到相关文章