【问题标题】:Json string to XmlJson 字符串到 Xml
【发布时间】:2019-03-22 14:13:55
【问题描述】:

我是一个新程序员,我真的被困住了(可能是新手,知识太少)我需要转换一个 json 字符串(类似这样):

[
  {
    "Start": "date",
    "Finish": "date",
    "Subject": "",
    "Comments": "",
    "Site": "address",
    "Location": null,
    "Status": false,
    "Arrived": true,
    "Noshow": false,
    "Services": "Initial Consultation",
    "Attendees": [
      {
        "AccountId": 1111,
        "AccountType": "MP",
        "Name": "MMS (FP), Support "
      },
      {
        "AccountId": 2220915,
        "AccountType": "PA",
        "Name": "Test, Patient "
      }
    ]
  },
]

像这样进入 XML:

<?xml version="1.0" encoding="UTF-8"?>
   <root>
   <element>
      <Arrived>true</Arrived>
      <Attendees>
         <element>
            <AccountId>1111</AccountId>
            <AccountType>MP</AccountType>
            <Name>MMS(FP), Support</Name>
         </element>
         <element>
            <AccountId>2220915</AccountId>
            <AccountType>PA</AccountType>
            <Name>Test, Patient</Name>
         </element>
      </Attendees>
      <Comments />
      <Finish>date</Finish>
      <Location null="true" />
      <Noshow>false</Noshow>
      <Services>Initial Consultation</Services>
      <Site>address</Site>
      <Start>date</Start>
      <Status>false</Status>
      <Subject />
   </element>
</root>`

并尝试谷歌搜索各种答案均无济于事。我已经尝试了 JsonConvert.DecryptXmlNode(filename); 的很多排列,但这些都通过错误。 我遇到的错误包括“根级别的数据无效”。和“只能转换以有效对象开头的 json”。

为了澄清起见,我收到了数百个 Json 文件(不知道其中有什么),需要一种“包罗万象”的场景。

提前谢谢你。

【问题讨论】:

  • 如果 xml 未加密,则无法解密。这就是您收到错误的原因。
  • 我使用 Newtonsoft 的。效果很好。
  • 有许多库可以将 JSON 转换为 XML,但它们很少能准确生成您想要的 XML。通常,必须使用将 XML 映射到所需格式的自定义转换(例如在 XSLT 中)来跟踪转换。这对一个 JSON 文件来说很容易,但是当你不知道其中的内容时,为数百个 JSON 文件做这件事并不容易。您需要更清楚地了解您生成的 XML 将如何使用,以及消费者的期望是什么。
  • JSON 有效。这是一个数组。这就是为什么 xml 使用 &lt;element&gt; 元素在根附近和 attendees 中保存值的原因@

标签: c# json xml


【解决方案1】:

在开始之前,我建议使用 https://jsonlint.com/ 验证您的 JSON。 外部方括号不是必需的,最好删除末尾的逗号。

现在,既然您提到您使用的是 C# 和 Newtonsoft Json.NET,您可以在控制台程序的 Program.cs 文件中尝试:

using System;
using System.Xml.Linq; //For the XDocument class
using Newtonsoft.Json; //For JsonConvert class
using System.IO; //For File class

class JsonToXMLProgram
{
    static void Main(string[] args)
    {
        string myJSONString = @File.ReadAllText(@"H:\MyJsonFile.json"); //Replace with your json files' locations.

        //This converts the JSON string to xml
        XDocument myXMLDocument = JsonToXML(myJSONString);

        //you could then check your xml by outputting it to the console...
        Console.WriteLine(myXMLDocument.ToString());
        //..or by saving the file to disk
        string myXMLFilePath = @"H:\MyXmlDocument.xml"; //Replace with the path to your generated xml files.
        myXMLDocument.Save(myXMLFilePath);
    }


    public static XDocument JsonToXML(string jsonString)
    {
        XDocument xmlDoc;
        try
        {
            xmlDoc = JsonConvert.DeserializeXNode(jsonString, "Root", true);
            return xmlDoc;
        }
        catch (JsonException e)
        {
            Console.WriteLine("There appears to be an error in the json file. Please validate the json to ensure that it is free from errors.");
            Console.WriteLine("Details: " + e.Message);
            return new XDocument();
        }
    }
}

【讨论】:

  • 外部方括号没有意义,但完全合法。倒数第二行的逗号是非法的,但被许多 JSON 解析器接受。
  • @MichaelKay 更新了答案以反映这一点,谢谢。
【解决方案2】:

你想要:

// Calling your JSON deserialization to create an array of dictionarys
var items = json.FromJson<Dictionary<string, object>[]>();
var xml = new XElement("root", 
                            items
                                .Select(it => new XElement("element", 
                                                    it.Select(el => ToXml(el.Key, el.Value)))));    

// method to create xml from a key value pair
XElement ToXml(string key, object item)
{
    if(item is JArray data){
        var items = data.ToString()
                        .FromJson<Dictionary<string, object>[]>();
        return new XElement(key, items.Select(dt => items
                                                    .Select(it => new XElement("element",
                                                            it.Select(el => ToXml(el.Key, el.Value))))));
    }
    return new XElement(key, item);
}

// In a separate class
public static class Extensions
{
    // This uses NewtonSoft.Json for deserialization
    public static T FromJson<T>(this string json)
    {
        var serializer = new JsonSerializer();
        using (var sr = new StringReader(json))
        using (var jr = new JsonTextReader(sr))
        {
            var result = serializer.Deserialize<T>(jr);
            return result;
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-26
    • 2020-09-23
    • 1970-01-01
    • 2017-11-28
    • 1970-01-01
    • 2019-10-29
    相关资源
    最近更新 更多