是否可以使用JsonReaderWriterFactory将XML转换为JSON,而无需使用DataContractJsonSerializer? [英] Is it possible to use JsonReaderWriterFactory to convert XML to JSON without using DataContractJsonSerializer?

查看:137
本文介绍了是否可以使用JsonReaderWriterFactory将XML转换为JSON,而无需使用DataContractJsonSerializer?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个通用例程,该例程接受任何有效的XML并将其转换为JSON,而无需了解基础数据类型.我知道使用Json.Net可以轻松完成此操作,也知道如何使用DataContractJsonSerializer进行此操作,但是我们的组织不使用Json.Net,并且DataContractJsonSerializer需要启用数据协定的对象类型.

I need a generic routine that takes any valid XML and converts it to JSON without knowing the underlying data type. I know that this is easily done with Json.Net and I also know how to do it with the DataContractJsonSerializer but our organisation doesn't use Json.Net and the DataContractJsonSerializer needs a Data Contract enabled object type.

我使用Json.Net的工作代码:

My working code using Json.Net:

XmlDocument document = new XmlDocument();
document.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(document);

我想使用的代码是使用JsonReaderWriterFactory而不是Json.Net:

The code I'd like to be able to use, using JsonReaderWriterFactory instead of Json.Net:

string jsonText = string.Empty;

MemoryStream stream = new MemoryStream();
StreamWriter streamWriter = new StreamWriter(stream);
streamWriter.Write(xml);
streamWriter.Flush();
stream.Position = 0;

using (XmlDictionaryWriter xmlWriter = JsonReaderWriterFactory.CreateJsonWriter(stream))
{
    object someObject = new object();
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(someObject.GetType());
    serializer.WriteObject(stream, someObject);
    xmlWriter.Flush();
    jsonText = Encoding.Default.GetString(stream.GetBuffer());
}

有没有办法解决这个问题?

Is there a way around this?

推荐答案

可惜的是Json.Net并不是一个选择-我们已经使用了很多年了,这太棒了.缺少手工进行本机解析和json生成的方法,没有很多快速的方法可以做到这一点.

Too bad the Json.Net isn't an option - we've used it for years now, and it's fantastic. Short of native parsing and json generation by hand, there's not a lot of fast ways to do this.

从此链接中查看代码:

  • http://www.phdcc.com/xml2json.htm (See section "XmlToJSON C# code", should be fairly quick)

此代码可以很容易地适应于类或扩展名,以转换XML文档(甚至只是将xml字符串解析为XML文档,然后返回json.

This code could easily be adapted to a class or even extension to convert an XML Document (or even just xml string being parsed into an XML document, then returning the json.

可以考虑的另一种方法是以下方法.它指定使用匿名类型,前提是您无法控制可以从XML反序列化的对象(并且您不想管理那些单独的类型).

Another approach to consider could be the following. It specifies using anonymous types assuming you don't have control of the objects that could be deserialized from XML (and you don't want to manage those separate types).

  1. 将XML转换为匿名类型(可能通过
  2. 使用JavascriptSerializer将匿名对象序列化为json

下面的代码示例显示了此技术:

The code sample below shows this techinique:

using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Data.Entity.Design.PluralizationServices;
using System.Globalization;

namespace Scratch
{
    class Program
    {
        static void Main(string[] args)
        {
            string xml = "<root><student><id>1</id></student><student><id>2</id></student></root>";
            string json = XmlToJson(xml);
            Console.WriteLine(json);
            Console.ReadKey(true);
        }

        // Using JavaScriptSerializer
        static string XmlToJson(string xml)
        {
            var obj = GetAnonymousType(xml);
            var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            return serializer.Serialize(obj);
        }

        // Adapted from: http://www.codeproject.com/Tips/227139/Converting-XML-to-an-dynamic-object-using-ExpandoO
        static dynamic GetAnonymousType(string xml, XElement node = null)
        {
            node = string.IsNullOrEmpty(xml) ? node : XDocument.Parse(xml).Root;
            IDictionary<String, dynamic> result = new ExpandoObject();
            var pluralizationService = PluralizationService.CreateService(CultureInfo.CreateSpecificCulture("en-us"));
            node.Elements().AsParallel().ForAll(gn =>
                {
                    var isCollection = gn.HasElements
                        && (gn.Elements().Count() > 1
                            && gn.Elements().All(e => e.Name.LocalName.ToLower() == gn.Elements().First().Name.LocalName)
                        || gn.Name.LocalName.ToLower() == pluralizationService.Pluralize(gn.Elements().First().Name.LocalName).ToLower());
                    var items = isCollection ? gn.Elements().ToList() : new List<XElement>() { gn };
                    var values = new List<dynamic>();
                    items.AsParallel().ForAll(i => values.Add((i.HasElements) ? GetAnonymousType(null, i) : i.Value.Trim()));
                    result[gn.Name.LocalName] = isCollection ? values : values.FirstOrDefault();
                });
            return result;
        }
    }
}

这篇关于是否可以使用JsonReaderWriterFactory将XML转换为JSON,而无需使用DataContractJsonSerializer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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