使用C#/ LINQ XML转换成JSON [英] Convert XML to JSON using C#/LINQ

查看:100
本文介绍了使用C#/ LINQ XML转换成JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我需要转换为JSON在服务器下面的XML文件。起初,我以为我会把它转换成一个字典,然后使用的JavaScriptSerializer把它变成JSON但由于每列可以有不同的值类型,我不认为它会工作。有没有人在C#中做过类似的事情/ LINQ?

我需要preserve的值类型每列(布尔,字符串,整数)。

我想AP preciate对此有什么意见,我只是开始使用XML。谢谢。

 <柱体和GT;
 <列名=KEY1数据类型=布尔>真< /列>
 <列名=键2数据类型=字符串>的Hello World< /列>
 <列名=KEY3数据类型=整数> 999 LT; /列>
< /专栏>


解决方案

 使用系统;
使用System.Linq的;
使用System.Web.Script.Serialization;
使用System.Xml.Linq的;类节目
{
    静态无效的主要()
    {
        VAR XML =
        @<柱体和GT;
          <列名=键1,数据类型=布尔>真< /列>
          <列名=键2,数据类型=串>的Hello World< /列>
          <列名=KEY3,数据类型=整型,> 999 LT; /列>
        < /列>中;
        VAR DIC =的XDocument
            .Parse(XML)
            .Descendants(列)
            .ToDictionary(
                C => c.Attribute(姓名)。价值,
                C => c.Value
            );
        。VAR JSON =新的JavaScriptSerializer()序列化(DIC);
        Console.WriteLine(JSON);
    }
}

生产:

  {键1:真,KEY2:Hello World的,KEY3:999}

显然,这将所有的值作为字符串。如果你想保持基本类型的语义,你可以做到以下几点:

 使用系统;
使用System.Linq的;
使用System.Web.Script.Serialization;
使用System.Xml.Linq的;类节目
{
    静态无效的主要()
    {
        VAR XML =
        @<柱体和GT;
          <列名=键1,数据类型=System.Boolean>真< /列>
          <列名=键2,数据类型=System.String>的Hello World< /列>
          <列名=KEY3,数据类型=System.Int32> 999 LT; /列>
        < /列>中;
        VAR DIC =的XDocument
            .Parse(XML)
            .Descendants(列)
            .ToDictionary(
                C => c.Attribute(姓名)。价值,
                C => Convert.ChangeType(
                    c.Value,
                    typeof运算(字符串).Assembly.GetType(c.Attribute(数据类型)。值为true)
                )
            );
        。VAR JSON =新的JavaScriptSerializer()序列化(DIC);
        Console.WriteLine(JSON);
    }
}

生产:

  {键1:真的,KEY2:Hello World的,KEY3:999}

如果你不能修改你需要将你的自定义类型和底层.NET类型之间进行转换的自定义函数的基本XML结构:

 使用系统;
使用System.Linq的;
使用System.Web.Script.Serialization;
使用System.Xml.Linq的;类节目
{
    静态无效的主要()
    {
        VAR XML =
        @<柱体和GT;
          <列名=键1,数据类型=布尔>真< /列>
          <列名=键2,数据类型=串>的Hello World< /列>
          <列名=KEY3,数据类型=整型,> 999 LT; /列>
        < /列>中;
        VAR DIC =的XDocument
            .Parse(XML)
            .Descendants(列)
            .ToDictionary(
                C => c.Attribute(姓名)。价值,
                C => Convert.ChangeType(
                    c.Value,
                    的GetType(c.Attribute(数据类型)。值)
                )
            );
        。VAR JSON =新的JavaScriptSerializer()序列化(DIC);
        Console.WriteLine(JSON);
    }    私有静态类型的GetType(字符串类型)
    {
        开关(类型)
        {
            案整型:
                返回typeof运算(INT);
            案字符串:
                返回typeof运算(字符串);
            案布尔:
                返回typeof运算(布尔);
            // TODO:添加要支持其他类型
            默认:
                抛出新NotSupportedException异常(
                    的String.Format(类型{0}不支持,类型)
                );
        }
    }
}

I have the following XML file that I need to convert to JSON in the server. Initially I thought I would convert it to a Dictionary and then use the JavaScriptSerializer to turn it into JSON but since each column could have a different value type, I don't think it would work. Has anyone done something similar before in C#/LINQ?

I need to preserve the Value Types(Boolean, String, Integer) of each column.

I would appreciate any advice on this as Im just starting to work with XML. Thanks.

<Columns>
 <Column Name="key1" DataType="Boolean">True</Column>
 <Column Name="key2" DataType="String">Hello World</Column>
 <Column Name="key3" DataType="Integer">999</Column>
</Columns>

解决方案

using System;
using System.Linq;
using System.Web.Script.Serialization;
using System.Xml.Linq;

class Program
{
    static void Main()
    {
        var xml = 
        @"<Columns>
          <Column Name=""key1"" DataType=""Boolean"">True</Column>
          <Column Name=""key2"" DataType=""String"">Hello World</Column>
          <Column Name=""key3"" DataType=""Integer"">999</Column>
        </Columns>";
        var dic = XDocument
            .Parse(xml)
            .Descendants("Column")
            .ToDictionary(
                c => c.Attribute("Name").Value, 
                c => c.Value
            );
        var json = new JavaScriptSerializer().Serialize(dic);
        Console.WriteLine(json);
    }
}

produces:

{"key1":"True","key2":"Hello World","key3":"999"}

Obviously this treats all the values as strings. If you want to keep the underlying type semantics you could do the following:

using System;
using System.Linq;
using System.Web.Script.Serialization;
using System.Xml.Linq;

class Program
{
    static void Main()
    {
        var xml = 
        @"<Columns>
          <Column Name=""key1"" DataType=""System.Boolean"">True</Column>
          <Column Name=""key2"" DataType=""System.String"">Hello World</Column>
          <Column Name=""key3"" DataType=""System.Int32"">999</Column>
        </Columns>";
        var dic = XDocument
            .Parse(xml)
            .Descendants("Column")
            .ToDictionary(
                c => c.Attribute("Name").Value, 
                c => Convert.ChangeType(
                    c.Value,
                    typeof(string).Assembly.GetType(c.Attribute("DataType").Value, true)
                )
            );
        var json = new JavaScriptSerializer().Serialize(dic);
        Console.WriteLine(json);
    }
}

produces:

{"key1":true,"key2":"Hello World","key3":999}

And if you cannot modify the underlying XML structure you will need a custom function that will convert between your custom types and the underlying .NET type:

using System;
using System.Linq;
using System.Web.Script.Serialization;
using System.Xml.Linq;

class Program
{
    static void Main()
    {
        var xml = 
        @"<Columns>
          <Column Name=""key1"" DataType=""Boolean"">True</Column>
          <Column Name=""key2"" DataType=""String"">Hello World</Column>
          <Column Name=""key3"" DataType=""Integer"">999</Column>
        </Columns>";
        var dic = XDocument
            .Parse(xml)
            .Descendants("Column")
            .ToDictionary(
                c => c.Attribute("Name").Value, 
                c => Convert.ChangeType(
                    c.Value, 
                    GetType(c.Attribute("DataType").Value)
                )
            );
        var json = new JavaScriptSerializer().Serialize(dic);
        Console.WriteLine(json);
    }

    private static Type GetType(string type)
    {
        switch (type)
        {
            case "Integer":
                return typeof(int);
            case "String":
                return typeof(string);
            case "Boolean":
                return typeof(bool);
            // TODO: add any other types that you want to support
            default:
                throw new NotSupportedException(
                    string.Format("The type {0} is not supported", type)
                );
        }
    }
}

这篇关于使用C#/ LINQ XML转换成JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆