从C#中的XML序列化时,向JSON添加空数组

时间:2018-08-02 12:42:55

标签: c# json xml serialization

我正在研究一个解析XML文档并对其进行序列化的应用程序。我能够解析并将其转换为JSON,但问题仍然存在。 我要实现的是,如果XML中不存在该元素节点,则在json中添加一个空数组结构。但是从我的代码中,输出为element : null

我到目前为止所做的-

我的课:

    [Serializable()]
    [XmlRoot("CarCollection")]
    public class CarCollection
    {
        [XmlArray("Cars")]
        [XmlArrayItem("Car", typeof(Car))]
        public Car[] Car { get; set; }
    }

    [Serializable()]
    public class Car
    {
        [XmlElement("StockNumber")]
        public string stockNumber { get; set; }

        [XmlElement("Make")]
        public string make { get; set; }

        [XmlArray("Models")]
        [XmlArrayItem("model", typeof(Model))]
        public Model[] Model { get; set; }

    }

    [Serializable()]
    public class Model
    {
        [XmlElement("modelName")]
        public string modelName { get; set; }

        [XmlElement("modelType")]
        public string modelType { get; set; }

        [XmlElement("price")]
        public string price { get; set; }

        [XmlElement("preOrderNeeded")]
        public string preOrderNeeded { get; set; }
    }
}

XML:

<?xml version="1.0" encoding="utf-8"?>
<CarCollection>
<Cars>
  <Car>
    <StockNumber>1020</StockNumber>
    <Make>Renault</Make>
    <Models>
       <model>
          <modelName>Kwid</modelName>
          <modelType>Basic</modelType>
          <price>5 Lakhs</price>
          <preOrderNeeded>No</preOrderNeeded>
       </model>
       <model>
          <modelName>Kwid</modelName>
          <modelType>Compact Model with all upgrades</modelType>
          <price>7.25 Lakhs</price>
          <preOrderNeeded>Yes</preOrderNeeded>
       </model>
    </Models>
  </Car>
  <Car>
    <StockNumber>1010</StockNumber>
    <Make>Toyota</Make>

  </Car>
</Cars>
</CarCollection>

我的序列化逻辑:

CarCollection cars = null;

XmlSerializer serializer = new XmlSerializer(typeof(CarCollection));
using (StreamReader sr = new StreamReader(@"C:\Users\someNAme\Downloads\XML\modelXML.xml"))
{
    cars = (CarCollection)serializer.Deserialize(sr);

    string output = JsonConvert.SerializeObject(cars);
}

这就是我得到的:

{
    "stockNumber": "1010",
    "make": "Toyota",
    "Model": null
}

我想要实现:

{
    "stockNumber": "1010",
    "make": "Toyota",
    "Model": []
}

1 个答案:

答案 0 :(得分:0)

您可以尝试Cinchoo ETL-一个开源库,如下所示进行xml-> json转换

using (var r = new ChoXmlReader("Sample49.xml")
    .WithXPath("/CarCollection/Cars/Car")
    )
{
    Console.WriteLine(ChoJSONWriter.ToTextAll(r));
}

输出:

[
 {
  "StockNumber": 1020,
  "Make": "Renault",
  "Models": [
   {
     "modelName": "Kwid",
     "modelType": "Basic",
     "price": "5 Lakhs",
     "preOrderNeeded": "No"
   }
   {
     "modelName": "Kwid",
     "modelType": "Compact Model with all upgrades",
     "price": "7.25 Lakhs",
     "preOrderNeeded": "Yes"
   }
  ]
 },
 {
  "StockNumber": 1010,
  "Make": "Toyota",
  "Models": []
 }
]

希望有帮助。