【问题标题】:Convert JSON to XML and save XML将 JSON 转换为 XML 并保存 XML
【发布时间】:2011-01-08 18:22:13
【问题描述】:

我正在尝试将一些 JSON 转换为 XML,然后在 C# 中使用 JSON.NET 保存它,但我似乎无法得到它。

这是我所拥有的:

using System.XML;
using Newtonsoft;

XmlDocument doc = (XmlDocument)Newtonsoft.Json.JsonConvert.DeserializeXmlNode(json);
XmlTextWriter writer = new XmlTextWriter("json.xml", null);
writer.Formatting = Formatting.Indented;
doc.Save(writer);

【问题讨论】:

  • 什么不起作用?有什么错误吗?例外?
  • 我发现了一个异常。 A first chance exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.Net35.dll
  • 这意味着它被Json.NET捕获和处理。你仍然没有解释什么不起作用。
  • 它不保存 XML 文件,我不确定它是否甚至将 JSON 转换为 XML。
  • 你进入代码了吗?你检查了不同的变量吗?调试是你的朋友。

标签: c# xml winforms json json.net


【解决方案1】:

我测试了你的代码,它对我来说完全没问题。根据DeserializeXmlNode 的文档,这绝对可以工作:

// { "?xml": { "@version": "1.0", "@standalone": "no" }, "root": { "person": [ { "@id": "1", "name": "Alan", "url": "http://www.google.com" }, { "@id": "2", "name": "Louis", "url": "http://www.yahoo.com" } ] } }
string json = "{ \"?xml\": { \"@version\": \"1.0\", \"@standalone\": \"no\" }, \"root\": { \"person\": [ { \"@id\": \"1\", \"name\": \"Alan\", \"url\": \"http://www.google.com\" }, { \"@id\": \"2\", \"name\": \"Louis\", \"url\": \"http://www.yahoo.com\" } ] } }";

System.Xml.XmlDocument xmlDocument = Newtonsoft.Json.JsonConvert.DeserializeXmlNode(json);
System.Xml.XmlTextWriter xmlTextWriter = new System.Xml.XmlTextWriter("json.xml", null);
xmlTextWriter.Formatting = System.Xml.Formatting.Indented;
xmlDocument.Save(xmlTextWriter);

//<?xml version="1.0" standalone="no"?>
//<root>
//  <person id="1">
//    <name>Alan</name>
//    <url>http://www.google.com</url>
//  </person>
//  <person id="2">
//    <name>Louis</name>
//    <url>http://www.yahoo.com</url>
//  </person>
//</root>

使用上面的 JSON 字符串测试您的方法,以验证它是否有效。我会说你的 JSON 无效有问题。

例如,您可以在此处验证您的 JSON:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-09
    • 2018-07-23
    • 1970-01-01
    相关资源
    最近更新 更多