将xml字符串反序列化为json,然后将json反序列化为object

时间:2016-12-22 14:44:11

标签: c# json xml json.net deserialization

我需要将xml字符串反序列化为json,然后将json反序列化为该对象。 我正在尝试这个:

将xml字符串转换为xmlDocument

XmlDocument doc = new XmlDocument();
        doc.LoadXml(xmlstring);

xmlstring已合成 然后将xml序列化为json

  var json = JsonConvert.SerializeXmlNode(doc, Formatting.Indented, true);

然后尝试将json字符串反序列化为我的对象

在这种情况下,变量“json”的值看起来像

 {
   "$type": "ESBSerializerTest.MyClass1, ESBSerializerTest",
   "strI1": "strI1",
   "intI1": "2",
   "Interface2s": {
     "$type": "System.Collections.Generic.List`1[[ESBSerializerTest.IInterface2, ESBSerializerTest]], mscorlib",
"$values": [
  {
    "$type": "ESBSerializerTest.MyClass2, ESBSerializerTest",
     "intI2": {
      "@xmlns": "",
      "#text": "111"
    }
  },
  {
    "$type": "ESBSerializerTest.MyClass2, ESBSerializerTest",
    "intI2": {
      "@xmlns": "",
      "#text": "222"
    }
  },
  {
    "$type": "ESBSerializerTest.MyClass2, ESBSerializerTest",
    "intI2": {
      "@xmlns": "",
      "#text": "333"
    }
  }
]}

并且json无法反序列化我的列表的值,因为它们应该如下所示:

{
    "$type": "ESBSerializerTest.MyClass2, ESBSerializerTest",
    "intI2": "111"
  },

Deserealizing:

var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All, ContractResolver = new ESBDynamicContractResolver(_kernel) };

        return JsonConvert.DeserializeObject<MyClass1>(json, settings);

 public class MyClass1 : IInterface1
{

    public string strI1 { get; set; }
    public int intI1 { get; set; }
    public List<MyClass2> Interface2s { get; set; }
    public int intC1 { get; set; }
}

0 个答案:

没有答案