我开始使用Json。NET将JSON格式的字符串转换为对象,反之亦然。在Json中我不确定。NET框架,它是可能的转换字符串在JSON到XML格式,反之亦然?


当前回答

我花了很长时间寻找公认解决方案的替代代码,希望不使用外部程序集/项目。感谢DynamicJson项目的源代码,我想到了以下内容:

public XmlDocument JsonToXML(string json)
{
    XmlDocument doc = new XmlDocument();

    using (var reader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(json), XmlDictionaryReaderQuotas.Max))
    {
        XElement xml = XElement.Load(reader);
        doc.LoadXml(xml.ToString());
    }

    return doc;
}

注意:出于xPath目的,我希望使用XmlDocument而不是XElement。 此外,这段代码显然只能从JSON转换为XML,有各种相反的方法。

其他回答

是的,你可以这样做(我这样做),但要注意转换时的一些矛盾,并适当地处理。您不能自动符合所有的接口可能性,并且在控制转换方面有有限的内置支持—许多JSON结构和值不能自动以两种方式转换。请记住,我使用的是Newtonsoft JSON库和MS XML库的默认设置,所以你的里程可能会有所不同:

XML -> json

All data becomes string data (for example you will always get "false" not false or "0" not 0) Obviously JavaScript treats these differently in certain cases. Children elements can become nested-object {} OR nested-array [ {} {} ...] depending if there is only one or more than one XML child-element. You would consume these two differently in JavaScript, etc. Different examples of XML conforming to the same schema can produce actually different JSON structures this way. You can add the attribute json:Array='true' to your element to workaround this in some (but not necessarily all) cases. Your XML must be fairly well-formed, I have noticed it doesn't need to perfectly conform to W3C standard, but 1. you must have a root element and 2. you cannot start element names with numbers are two of the enforced XML standards I have found when using Newtonsoft and MS libraries. In older versions, Blank elements do not convert to JSON. They are ignored. A blank element does not become "element":null

一个新的更新改变了如何处理null(感谢Jon Story指出):https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_NullValueHandling.htm

Json -> XML

您需要一个将转换为根XML元素的顶级对象,否则解析器将失败。 您的对象名称不能以数字开头,因为它们不能转换为元素(XML技术上甚至比这更严格),但我可以“逃避”打破一些其他元素命名规则。

请随时提到你注意到的任何其他问题,我已经开发了自己的自定义例程,用于准备和清理字符串,因为我来回转换。你的情况可能需要也可能不需要准备/清理。正如StaxMan提到的,您的情况实际上可能需要您在对象之间进行转换……这可能需要适当的接口和一堆case语句/等等来处理我上面提到的警告。

对于转换JSON字符串到XML尝试:

    public string JsonToXML(string json)
    {
        XDocument xmlDoc = new XDocument(new XDeclaration("1.0", "utf-8", ""));
        XElement root = new XElement("Root");
        root.Name = "Result";

        var dataTable = JsonConvert.DeserializeObject<DataTable>(json);
        root.Add(
                 from row in dataTable.AsEnumerable()
                 select new XElement("Record",
                                     from column in dataTable.Columns.Cast<DataColumn>()
                                     select new XElement(column.ColumnName, row[column])
                                    )
               );


        xmlDoc.Add(root);
        return xmlDoc.ToString();
    }

要将XML转换为JSON,请尝试以下方法:

    public string XmlToJson(string xml)
    {
       XmlDocument doc = new XmlDocument();
       doc.LoadXml(xml);

       string jsonText = JsonConvert.SerializeXmlNode(doc);
       return jsonText;
     }

是的。使用包含辅助方法的JsonConvert类来实现这个精确的目的:

// To convert an XML node contained in string xml into a JSON string   
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);

// To convert JSON text contained in string json into an XML node
XmlDocument doc = JsonConvert.DeserializeXmlNode(json);

这里的文档:使用JSON在JSON和XML之间转换。网

我已经使用下面的方法将JSON转换为XML

List <Item> items;
public void LoadJsonAndReadToXML() {
  using(StreamReader r = new StreamReader(@ "E:\Json\overiddenhotelranks.json")) {
    string json = r.ReadToEnd();
    items = JsonConvert.DeserializeObject <List<Item>> (json);
    ReadToXML();
  }
}

And

public void ReadToXML() {
  try {
    var xEle = new XElement("Items",
      from item in items select new XElement("Item",
        new XElement("mhid", item.mhid),
        new XElement("hotelName", item.hotelName),
        new XElement("destination", item.destination),
        new XElement("destinationID", item.destinationID),
        new XElement("rank", item.rank),
        new XElement("toDisplayOnFod", item.toDisplayOnFod),
        new XElement("comment", item.comment),
        new XElement("Destinationcode", item.Destinationcode),
        new XElement("LoadDate", item.LoadDate)
      ));

    xEle.Save("E:\\employees.xml");
    Console.WriteLine("Converted to XML");
  } catch (Exception ex) {
    Console.WriteLine(ex.Message);
  }
  Console.ReadLine();
}

我使用名为Item的类来表示元素

public class Item {
  public int mhid { get; set; }
  public string hotelName { get; set; }
  public string destination { get; set; }
  public int destinationID { get; set; }
  public int rank { get; set; }
  public int toDisplayOnFod { get; set; }
  public string comment { get; set; }
  public string Destinationcode { get; set; }
  public string LoadDate { get; set; }
}

它的工作原理……

感谢David Brown的回答。在JSON的例子中。Net 3.5中,转换方法在JsonConvert静态类下:

XmlNode myXmlNode = JsonConvert.DeserializeXmlNode(myJsonString); // is node not note
// or .DeserilizeXmlNode(myJsonString, "root"); // if myJsonString does not have a root
string jsonString = JsonConvert.SerializeXmlNode(myXmlNode);