XML到JSON - 将Json对象转换为Json数组

时间:2017-11-03 11:51:39

标签: c# json xml serialization json.net

在我的控制器中,我正在将XML数据转换为JSON,就像这样

 var doc = new XmlDocument();
 doc.Load(xmlStream);
 doc.DocumentElement.RemoveAttribute("xmlns"); // don't want xmlns node in json

 return Json(doc.DocumentElement.ChildNodes, new JsonSerializerSettings { StringEscapeHandling = StringEscapeHandling.Default }, Encoding.UTF8);

XML看起来像这样

<Employees xmlns="http://company.com/schemas">
    <Employee>
        <FirstName>name1</FirstName>
        <LastName>surname1</LastName>
    <Employee>
    <Employee>
        <FirstName>name2</FirstName>
        <LastName>surname2</LastName>
    <Employee>
    <Employee>
        <FirstName>name3</FirstName>
        <LastName>surname3</LastName>
    <Employee>
</Employees>

输出JSON

[
    {
        "Employee": {
            "FirstName": "name1",
            "LastName": "surname1"
         }
    },
    {
        "Employee": {
            "FirstName": "name2",
            "LastName": "surname2"
         }
    },{
        "Employee": {
            "FirstName": "name3",
            "LastName": "surname3"
         }
    }
]

我想要实现的目标

[
    {
        "FirstName": "name1",
        "LastName": "surname1"
    },
    {
        "FirstName": "name2",
        "LastName": "surname2"
    },{
        "FirstName": "name3",
        "LastName": "surname3"
    }
]

那么将XML元素序列化为JSON时,有没有办法将XML元素转换为JSON数组?我想让它变得动态,所以我不想在这样做时编写实体类。

3 个答案:

答案 0 :(得分:2)

我的预期输出应该不远。我认为我们可以做得更好,但这是我的两行解决方案:

Try it online!

var doc = XDocument.Parse(xmlData);
var json = JsonConvert.SerializeXNode(doc);

输出:

{
  "Employees": {
    "@xmlns": "http://company.com/schemas",
    "Employee": [{
      "FirstName": "name1",
      "LastName": "surname1"
    }, {
      "FirstName": "name2",
      "LastName": "surname2"
    }, {
      "FirstName": "name3",
      "LastName": "surname3"
    }]
  }
}

从@Peter编辑:

由于模式是常量,因此可以导航对象以到达对象:

var employees = JObject.Parse(json).Children().Children().Children().ElementAt(1).Children().First();

Try it online!

答案 1 :(得分:0)

如果你之前在对象数组中反序列化它是可能的。 像这样:

    class Employee
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    static void DoXmlToJson()
    {
        string xmlData = @"<?xml version='1.0' encoding='UTF-8'?>
                          <Employees>
                            <Employee>
                                <FirstName>name1</FirstName>
                                <LastName>surname1</LastName>
                            </Employee>
                            <Employee>
                                <FirstName>name2</FirstName>
                                <LastName>surname2</LastName>
                            </Employee>
                            <Employee>
                                <FirstName>name3</FirstName>
                                <LastName>surname3</LastName>
                            </Employee>
                        </Employees>";

        XDocument doc = XDocument.Parse(xmlData);
        var array = doc.Root.Elements()
            .Select(row => new Employee() {
                FirstName = row.Element("FirstName").Value,
                LastName = row.Element("LastName").Value
            });

        string json = JsonConvert.SerializeObject(array);

        Console.WriteLine(json);
    }

使用XmlSerializer.Deserialze的另一种方法:

    public class Employee
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
    public class Employees
    {
        [XmlElement("Employee")]
        public Employee[] Items { get; set; }
    }

    static void DoXmlToJson()
    {
        string xmlData = @"<Employees>
                            <Employee>
                                <FirstName>name1</FirstName>
                                <LastName>surname1</LastName>
                            </Employee>
                            <Employee>
                                <FirstName>name2</FirstName>
                                //<LastName>surname2</LastName>
                            </Employee>
                            <Employee>
                                <FirstName>name3</FirstName>
                                <LastName>surname3</LastName>
                            </Employee>
                        </Employees>";


        XmlSerializer xmlSerializer = new XmlSerializer(typeof(Employees));
        MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlData));
        Employees wholeObject = (Employees)xmlSerializer.Deserialize(memoryStream);

        string json = JsonConvert.SerializeObject(wholeObject.Items);

        Console.WriteLine(json);
    }

在这两种情况下,输出都看起来像这样:

[
  {
    "FirstName": "name1",
    "LastName": "surname1"
  },
  {
    "FirstName": "name2",
    "LastName": "surname2"
  },
  {
    "FirstName": "name3",
    "LastName": "surname3"
  }
]

答案 2 :(得分:0)

使用Cinchoo ETL - 一个开源库,您可以使用几行代码轻松地将Xml转换为Json

string xml = @"<Employees xmlns=""http://company.com/schemas"">
    <Employee>
        <FirstName>name1</FirstName>
        <LastName>surname1</LastName>
    </Employee>
    <Employee>
        <FirstName>name2</FirstName>
        <LastName>surname2</LastName>
    </Employee>
    <Employee>
        <FirstName>name3</FirstName>
        <LastName>surname3</LastName>
    </Employee>
</Employees>
";

StringBuilder sb = new StringBuilder();
using (var p = ChoXmlReader.LoadText(xml)
    )
{
    using (var w = new ChoJSONWriter(sb))
        w.Write(p);
}

Console.WriteLine(sb.ToString());

输出:

[
 {
  "FirstName": "name1",
  "LastName": "surname1"
 },
 {
  "FirstName": "name2",
  "LastName": "surname2"
 },
 {
  "FirstName": "name3",
  "LastName": "surname3"
 }
]

Checkout CodeProject文章提供了一些额外的帮助。

免责声明:我是这个图书馆的作者。