通过将键映射为类的字段并将#text作为该字段的值来将json转换为对象

时间:2015-05-05 10:15:00

标签: c# .net json

虽然有很多链接可以将json转换为对象,但这里的要求有点不同。

我有这个xml -

{
  "structure": {
    "-type": "DivideByZeroException",
    "property": [
      {
        "-key": "Message",
        "#text": "Attempted to divide by zero."
      },
      { "-key": "Data" },
      { "-key": "InnerException" },
      {
        "-key": "TargetSite",
        "#text": "Void btnWriteError_Click(System.Object, System.Windows.RoutedEventArgs)"
      },
      {
        "-key": "StackTrace",
        "#text": "   at WpfApplication1.MainWindow.btnWriteError_Click(Object sender, RoutedEventArgs e) in c:\\Users\\Anil.Purswani\\Desktop\\WPF_Application\\WpfApplication1\\MainWindow.xaml.cs:line 169"
      },
      { "-key": "HelpLink" },
      {
        "-key": "Source",
        "#text": "WpfApplication1"
      },
      {
        "-key": "HResult",
        "#text": "-2147352558"
      }
    ]
  }
}

并希望将其转换为 -

Class ModelError
{
   string Message;
   Exception InnerException;
   string TargetSite;
   string StackTrace;
   string HelpLink;
   string Source;
   string HResult;
}

所以最终的对象应该包含这样的内容 -

modelerrorobj.Message =  "Attempted to divide by zero."
modelerrorobj.Data = null;
modelerrorobj.InnerException = null;
modelerrorobj.Targetsite = "Void btnWriteError_Click(System.Object, System.Windows.RoutedEventArgs)";
modelerrorobj.StackTrace = "   at WpfApplication1.MainWindow.btnWriteError_Click(Object sender, RoutedEventArgs e) in c:\\Users\\Anil.Purswani\\Desktop\\WPF_Application\\WpfApplication1\\MainWindow.xaml.cs:line 169"

基本上,“ - key”值,即“Message”,“Data”,“StackTrace”是ModelError类中的字段,“#text”是该对应字段的值。

例如。

      {
        "-key": "Message",
        "#text": "Attempted to divide by zero."
      },

在上面,“消息”是字段,“试图除以零”。是该领域的价值。

请注意我有Json但是如何在ModelError中转换它?

0 个答案:

没有答案