gpt4 book ai didi

c# - Json 属性作为节点生成

转载 作者:行者123 更新时间:2023-12-04 02:17:24 27 4
gpt4 key购买 nike

我需要将传入的 json 文件转换为 XML。

我正在使用以下代码来实现要求。我正在使用 Newtonsoft Json 转换器

 XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);

输入文件是

{"menu": {   "id": "file",   "value": "File",   "popup": {     "menuitem": [       {"value": "New", "onclick": "CreateNewDoc()"},       {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"}  ]  }}}

我得到的输出是

<menu><id>file</id><value>File</value><popup><menuitem><value>New</value><onclick>CreateNewDoc()</onclick></menuitem><menuitem><value>Open</value><onclick>OpenDoc()</onclick></menuitem><menuitem><value>Close</value><onclick>CloseDoc()</onclick></menuitem></popup></menu>

所以这里的属性是作为节点生成的。

提前致谢

最佳答案

来自 Converting between JSON and XML :

Conversion Rules

  • Attributes are prefixed with an @ and should be at the start of the object.

因此你可以使用 Linq to JSON使用原始值修改所有 JSON 属性,并在它们的名称前添加一个 @ 字符。请注意,由于您的文件将“以 MB 为单位”,因此您应该避免加载到临时字符串,而是 stream the file contents in directly :

        // Load the JObject directly from a file
using (var streamReader = File.OpenText(fileName))
using (var jsonReader = new JsonTextReader(streamReader))
{
obj = JObject.Load(jsonReader);
}

// Rename all properties with primitive values (string, number, boolean, null) to begin with "@"
foreach (var o in obj.Descendants().OfType<JObject>())
{
// Attributes must appear first in the JObject's property list.
int insertIndex = 0;
foreach (var property in o.Properties().Where((p => p.Value is JValue && !p.Name.StartsWith("@"))).ToList())
{
property.Remove();
((IList<JToken>)o).Insert(insertIndex++, new JProperty("@" + property.Name, property.Value));
}
}

// Convert to XmlDocument
XmlDocument doc;
using (var reader = obj.CreateReader())
{
doc = (XmlDocument)JsonExtensions.DeserializeXmlNode(reader);
}

使用辅助方法:

public static class JsonExtensions
{
public static XmlDocument DeserializeXmlNode(JsonReader reader)
{
return DeserializeXmlNode(reader, null, false);
}

public static XmlDocument DeserializeXmlNode(JsonReader reader, string deserializeRootElementName, bool writeArrayAttribute)
{
var converter = new Newtonsoft.Json.Converters.XmlNodeConverter() { DeserializeRootElementName = deserializeRootElementName, WriteArrayAttribute = writeArrayAttribute };
var jsonSerializer = JsonSerializer.CreateDefault(new JsonSerializerSettings { Converters = new JsonConverter[] { converter } });
return (XmlDocument)jsonSerializer.Deserialize(reader, typeof(XmlDocument));
}
}

这会产生输出:

<menu id="file" value="File">
<popup>
<menuitem value="New" onclick="CreateNewDoc()" />
<menuitem value="Open" onclick="OpenDoc()" />
<menuitem value="Close" onclick="CloseDoc()" />
</popup>
</menu>

关于c# - Json 属性作为节点生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33086709/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com