在C#中将sql xml转换为json转换时如何处理单元素json数组?

时间:2018-11-23 07:01:21

标签: c# .net json xml

我正在使用C#将SQL输出XML转换为JSON转换。当我将具有多个set元素的XML转换为JSON时,输出(如JSON数组)同时XML具有单个单个集合,然后输出如JSON对象。在两种情况下如何将输出保持为JSON数组?

情况1:

<root>
   <DATA>
    <NAME>NAYAN</NAME>
    <LOCATION>CHENNAI</LOCATION>
  </DATA>
   <DATA>
    <NAME>TARA</NAME>
    <LOCATION>CHENNAI</LOCATION>
  </DATA>
 </root> 

结果:

{
   "DATA": [
      {
         "NAME": "NAYAN",
         "LOCATION": "CHENNAI"
      },
      {
         "NAME": "TARA",
         "LOCATION": "CHENNAI"
      }
   ]
}

情况2:

<root>
   <DATA>
    <NAME>NAYAN</NAME>
    <LOCATION>CHENNAI</LOCATION>
  </DATA>
 </root>

结果:

{
   "DATA": {
      "NAME": "NAYAN",
      "LOCATION": "CHENNAI"
   }
}

期望:

{
   "DATA":[
 {
      "NAME": "NAYAN",
      "LOCATION": "CHENNAI"
   }
]
}

这是我的C#代码:

static void Main(string[] args)
{
    string xml = @"<root>
      <DATA>
        <NAME>NAYAN</NAME>
        <LOCATION>CHENNAI</LOCATION>
      </DATA>
    </root>";

    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xml);

    string json = JsonConvert.SerializeXmlNode(doc,Newtonsoft.Json.Formatting.Indented,true);

    Console.WriteLine(json);
}

1 个答案:

答案 0 :(得分:1)

这里,我创建了一个简单的实用程序函数,如果DATA包含对象或数组,则可以使用您的DATA令牌并将其解析为Array。

public class Utility
{
    public static string JsonParser(string json)
    {
        JToken jTokenMain = JToken.Parse(json);

        JToken jToken = jTokenMain["DATA"];

        List<object> list = new List<object>();

        if (jToken is JArray)
        {
            list = jToken.ToObject<List<object>>();
        }
        else if (jToken is JObject)
        {
            list.Add(jToken.ToObject<object>());
        }

        JToken data = JToken.FromObject(list);

        jTokenMain["DATA"] = data;

        return jTokenMain.ToString();
    }
}

您可以使用上述功能,例如

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);

string json = JsonConvert.SerializeXmlNode(doc, Newtonsoft.Json.Formatting.Indented, true);

string formattedJson = Utility.JsonParser(json);    

编辑:

在您的xml中,<root>是第0级元素,<DATA>是第1级元素,它的名称可以是任何东西,并且您希望此元素在json中为Array,无论它是对象还是xml中的数组

XDocument doc = XDocument.Parse(xml);
//XDocument doc = XDocument.Load(@"Path to your xml");

Dictionary<string, object> dict = doc.Root.Elements()
   .GroupBy(x => x.Name.LocalName, y => new
   {
       Name = y.Element("NAME").Value,
       Location = y.Element("LOCATION").Value
   })
   .ToDictionary(x => x.Key, y => (object)y.ToList());

string json = JsonConvert.SerializeObject(dict);

Console.WriteLine(json);

情况1:(第一级元素名称为DATA

<root>
<DATA>
  <NAME>NAYAN</NAME>
  <LOCATION>CHENNAI</LOCATION>
</DATA>
</root>

输出:(密钥名称为DATA的Json)

enter image description here

情况2:(第一级元素名称为SAMPLE

<root>
<SAMPLE>
  <NAME>NAYAN</NAME>
  <LOCATION>CHENNAI</LOCATION>
</SAMPLE>
</root>

输出:(密钥名称为SAMPLE的Json)

enter image description here